Search code examples
javascriptreactjsreduxgetstore

How to get request data from axios.get to Redux store


I'm new in Redux. Can somebody explain, how can I get request data from Get

componentDidMount() {
        axios.get('/api/v3/products', {
            params: {
                pageNumber: 1,
                pageSize: 500,
            }
        })
            .then(response => {
                this.setState({result: response.data});
            })
            .catch(function (error) {
                console.log('error TestMethod', error);
            })
            .then(function () {
                // always executed
            });
    }

And place it in store in Redux

const initState = {
    products: [
        {id: 1, title: 'first'},
        {id: 2, title: 'second'},
        {id: 3, title: 'third'},
        {id: 4, title: 'fourth'},
        {id: 5, title: 'fifth'},
    ],
};

Are there any methods?


Solution

  • Inside reducer place a case in switch say...

    case FETCH_DATA: { 
      return {...state, data: action.payload}
    }
    

    Now you have reducer code in place. Inside then block dispatch action {type:FETCH_DATA, payload:response.data}

    .then(response => {
                this.setState({result: response.data});
            })