I'm developing an app, for the fronted i'm using next.js, and i had problem trying to stringify an object, this is how the error looks like
Argument of type '{ auth: dataObject; }' is not assignable to parameter of type 'string'
So what happens is that when a user log in i'm trying to save some data localStorage, and as far as i know, if you save data there it must be as a tring ( i really don't know why ) so that's why i'm using json.stringify ( in my code ).
Now, to give you more context, let me show you my code
This is my context - useReducer part ( the problem is in LOGIN case ! )
import { createContext } from "react";
import {
Actions,
dataObject,
LOGIN,
LOGOUT,
LOADING
} from "../GlobalInterfaces/AuthContextInterfaces";
import { useReducer } from "react";
import { useContext } from "react";
interface Istate {
loading: boolean;
data?: dataObject | null;
}
const DefaultState = createContext<Istate>({ loading: false });
const DispatchActions = createContext(null);
const localReducer = (state: Istate, action: Actions): Istate => {
switch (action.type) {
case LOADING:
return {
...state,
loading: true
};
case LOGIN:
JSON.stringify(localStorage.setItem("Auth", { auth: action.payload }));
return {
...state,
loading: false,
data: action.payload
};
case LOGOUT:
localStorage.removeItem("Auth");
return {
...state,
data: null
};
default:
return state;
}
};
export const AuthContext = ({ children }: { children: React.ReactNode }) => {
const [state, dispatch] = useReducer(localReducer, {
loading: false,
data: null
});
return (
<DefaultState.Provider value={state}>
<DispatchActions.Provider value={dispatch}>
{children}
</DispatchActions.Provider>
</DefaultState.Provider>
);
};
export const AuthData = () => useContext(DefaultState);
export const AuthActions = () => useContext(DispatchActions);
And these are my types and interfaces that i'm using with useContext and useReducer
// Data
export type dataObject = {
token: string;
user: { id: string; email: string; name: string };
};
// Options's Actions
export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const LOADING = "LOADING";
interface IloginAuth {
type: typeof LOGIN;
payload: dataObject;
}
interface IloginLogout {
type: typeof LOGOUT;
}
interface Iloading {
type: typeof LOADING;
}
export type Actions = IloginAuth | IloginLogout | Iloading;
SO what can i do to fix my code ? can i skip the JSON.stringify ?
Thanks for your time !