nemoxi
nemoxi

Reputation: 620

How to make a post request with axios (React Redux Hook)?

I want to set up a post request with axios (React Redux Hook).

How can I use my action with my form? Do you have a tutorial?

knowing of course that the form is a basic form with an onSubmit.

Here is my redux action:

export const createUserSuccess = (data) => {
    return {
        type: types.ADD_USERS_SUCCESS,
        payload: data,
    }
}

export const createUserError = (data) => {
    return {
        type: types.ADD_USERS_ERROR,
        payload: data
    }
}

export const createUser = (user) => {
    const userData = {
        id: [0],
        firstName: user.firstName,
        lastName: user.lastName,
        password: user.password,
        emailAddress: user.emailAddress,
    }
    return (dispatch) => {
        return axios.post('/users', userData, {headers: authHeader()})
            .then(response => {
                const id = response.data.id
                axios.get(`/users/${id}`, {headers: authHeader()})
                    .then(response => {
                        const data = response.data
                        dispatch(createUserSuccess(data))
                        history.push('/')
                    })
                    .catch(error => {
                        debugger
                        const errorPayload = {}
                        console.log(errorPayload, error)

                        errorPayload['message'] = error.response.data['hydra:description'];
                        errorPayload['error'] = error.response.status
                        dispatch(createUserError(errorPayload))
                    })
            })
            .catch(error => {
                const errorPayload = {}

                errorPayload['message'] = error.response.data['detail'];
                errorPayload['error'] = error.response.status
                dispatch(createUserError(errorPayload))
                console.log(error.response.data)
            })
    }
}

Upvotes: 0

Views: 1205

Answers (1)

Jaysidh Dumbali
Jaysidh Dumbali

Reputation: 21

Creating post request with Axios is very straightforward.

https://github.com/axios/axios#axios-api

For integrating with redux I recommend using Redux Toolkit. It comes with Redux Thunk as middleware and provides callbacks for handling all sorts of data manipulation in the redux store.

Guide for the can be found here - Redux Toolkit

Upvotes: 1

Related Questions