javascriptreactjscookieslocal-storagereact-cookie

page is getting redirected without setting value in state and in localstorage in react


const [userid, setUserId] = useState()
const handleSubmit = (e) => {
    e.preventDefault()
    axios.post('http://localhost:3001/Signin', { email, password })
        .then(result => {
            if (result.data.message === "Successfully Login") {
                setUserId(((result.data.ID).toString()))
                if(userid === result.data.ID){
                    navigate('/')
                }
            }
        })
        .catch(err => console.log(err))
}

useEffect(() => {
    localStorage.setItem('UserID' , userid)
},[])

Here whats happening is there is an sign in form which collects data and on click of button that details are being checked in mongoose and from there i am getting an id from result so now i want to store that id in localstorage then i want to redirect to the home page which is navigate('/').

But here page is being redirected without the data is set into a localstorage .

can anyone help me with this. i am learning react so dont have much idea about it.

Thank you in advance.


Solution

  • The issue you're facing is likely due to the asynchronous nature of JavaScript. When you call localStorage.setItem('UserID', userId), it's executed immediately after setting userid using setUserId, but setUserId is an asynchronous function, and the value of userid might not be updated by the time localStorage.setItem is called.

    To fix this, you should use the useEffect hook to watch for changes to userId and then set the item in localStorage.

    Here's an updated version of your code:

    const [userId, setUserId] = useState('');
    const handleSubmit = (e) => {
        e.preventDefault();
        axios.post('http://localhost:3001/Signin', { email, password })
            .then(result => {
                if (result.data.message === "Successfully Login") {
                    const userIdString = (result.data.ID).toString();
                    setUserId(userIdString);
                }
            })
            .catch(err => console.log(err));
    }
    
    useEffect(() => {
        if (userId) {
            localStorage.setItem('UserID', userId);
            navigate('/');
        }
    }, [userId]);
    

    In this code, I've added a dependency array [userId] to the useEffect, so it only runs when userid changes. When userid is updated after a successful login, the useEffect will set the UserID in localStorage and then trigger the navigation to the home page.