B
B
bzotsss2021-09-01 11:41:51
React
bzotsss, 2021-09-01 11:41:51

Why is no value coming to useState? Async?

Hello everyone, can anyone tell me why the statusText value does not come to useState ? I understand that this is most likely related to asynchronous, but I don’t understand how to explain it and what needs to be done so that everything works as I intended. If it's not difficult for anyone, can you please suggest / throw something to read on this topic? For as I understand useState is faster than useSelector , so what happens? The value comes to statusText as it should.

const ProfileStatus = () => {
    const dispatch = useDispatch()  
    useEffect(() => {
        dispatch(getStatusThunk())
    }, [])
    const statusText = useSelector(store => store.profilePage.profileStatus)
    const [editMode,
        setEditMode] = useState(false)
    const [status,
        setStatus] = useState(statusText)
    return (
        <div>
            <div>
                <img alt="user photo" src={userImg} />
            </div>
            <div>
                <span>{status}</span>
                <button onClick={() => setEditMode(!editMode)}>Change Status</button>
                <button onClick={() => dispatch(updateStatusThunk())}>Save Status</button>
            </div>
            <div>
                {editMode
                    ? <input
                        onChange={(e) => {
                            let text = e.target.value;
                            setStatus(text)
                        }}
                        value={status} />
                    : null}
            </div>
        </div>
    );
}
export default ProfileStatus;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-01
@bzotsss

useState comes with statusText , but useState only remembers it the first time the component is created. After that there are two statuses - the one in useState and the one in redux. And they don't interact with each other. Those. when getStatusThunk updates the status in redux, the status state doesn't care.
Here you need to decide - either use only the redux status, or synchronize them with each other. Depends on the task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question