E
E
EmKotlety2021-07-30 06:29:03
React
EmKotlety, 2021-07-30 06:29:03

How to properly use the useHistory hook?

When trying to redirect, we get the error "Invalid Hook Call Warning". I revised all methods with versions of react and router-dom. Maybe I overlooked something. Everything worked without useHistory

export const createPostFunction = (form) => {
    
    return async dispatch => {
        let history = useHistory()
        dispatch(setLoader()) 
        try {
            const response = await axios.post(`http://localhost:5000/api/auth/create`,
            {...form},
            {headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}},
                
            )
            const newPost = response.data.post
            dispatch(createPost(newPost))
            console.log('мы тута2')
            
            history.push('/links')
            localStorage.setItem('token', response.data.token)
        } catch (e) {
            dispatch(disableLoader());
            console.log(e)
            
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Lewandowski, 2021-07-30
@EmKotlety

The hook must be called when the component is rendered, and every time. You obviously don't. Use useHistoryin the component itself, and pass it as an argument to this function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question