0

I have two initial state posts and users. I am able to update the state of posts but not of users. I am using the JWT to send the token from the server-side to the client-side. When I console out the response received after sending the axios post request to /login, I am able to get the token sent from the server. But, when I set the state of users using the reducer function as action.payload and send it to the Login.js I am getting the users value as [].

const initialValue = {
    posts: [],
    users: []
}

const reducer = (state, action) => {
    switch (action.type) {
        case 'LOGIN':
            return {
                ...state,
                users: [action.payload]
            }
        default:
            return state
    }
}

export const Globalcontext = createContext(initialValue)

function App() {

    const [state, dispatch] = useReducer(reducer, initialValue)
    function login(User) {
        axios.post(`http://localhost:4000/blog/login`, User).then(res => {
            dispatch({
                type: 'LOGIN',
                payload: res.data
            })
            console.log(res.data) /* I am getting the desired token value */
        }).catch(err => {
            console.log(err)
        })
    }

After receiving the users state I am trying to set the localStorage item value to that state so that I can authenticate the user.


const Login = () => {
    let history = useHistory();
    const [email, setemail] = useState('');
    const [password, setpassword] = useState('');

    const { login, users } = useContext(Globalcontext);

    const handleSubmit = (e) => {
        e.preventDefault();

        const addedValue = {
            email,
            password,
        };

        localStorage.setItem('usertoken', users);
        console.log(localStorage.getItem('usertoken')); /* Here, I am getting [] as the output. */
        login(addedValue);

        setemail('');
        setpassword('');
        history.push('/blog');
    };
    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input
                    type='email'
                    name='email'
                    value={email}
                    placeholder='E-mail address'
                    onChange={(e) => setemail(e.target.value)}
                />
                <input
                    type='password'
                    name='password'
                    value={password}
                    placeholder='Password'
                    onChange={(e) => setpassword(e.target.value)}
                />
                <button
                    className='btn btn-secondary'
                    style={{ backgroundColor: '#007bff', margin: '5px' }}
                    type='submit'
                    value='submit'
                >
                    Login
                </button>
            </form>
        </div>
    );
};

export default Login;

critrange
  • 5,652
  • 2
  • 16
  • 47

0 Answers0