how to use redux thunk to fetch data

357 Views Asked by At

guys hope you all are doing great, Well I am using redux and I am not getting my result, I would like to describe my issue step by step I hope it will bater for understanding
(1) POSTMAN RESULT (i) get request , (ii) JSON data

enter image description here

Here is the code of itemList.jsx

const ItemList = (props) => {
    // this value is coming from parent component and here it's value is 1
    //as in postman data 
    const value = props.myData
    console.log(`value is ${value}`)

    const dispatch = useDispatch();

    const { rows } = useSelector(state => state.product);
    console.log(rows)

    useEffect((value) => { // value = 1
        console.log(` hello world ${value}`)

        const jsondata = { "categoryId_fk": 1 } // i am not sure that i would have to pass data like it 
        console.log(`this is my new console ${jsondata}`)
        dispatch(getProductByCategory(jsondata));

    }, [dispatch])

Here is the code of productAction.js //product Action

import axios from 'axios';
import {
    GET_PRODUCTS_BY_CATEGORY_REQUEST,
    GET_PRODUCTS_BY_CATEGORY_SUCCESS,
    GET_PRODUCTS_BY_CATEGORY_SUCCESS_FAIL,

    CLEAR_ERRORS
} from '../Constrants/ProductConstrants.js'
console.log('hello world')
export const getProductByCategory = (categoryId_fk) => async(dispatch)=>{
    console.log(categoryId_fk)
    try {
        dispatch({type: GET_PRODUCTS_BY_CATEGORY_REQUEST})
        const{ data } = await axios.get('/api/v1/catproduct',categoryId_fk)
        console.log(data)
        dispatch({
            type: GET_PRODUCTS_BY_CATEGORY_SUCCESS,
            payload: data
        })

    } catch (error) {
        dispatch({
            type:GET_PRODUCTS_BY_CATEGORY_SUCCESS_FAIL,
            payload: error.response.data.message
        })
    }
}

here is the code of productReducer

import {
    GET_PRODUCTS_BY_CATEGORY_REQUEST,
    GET_PRODUCTS_BY_CATEGORY_SUCCESS,
    GET_PRODUCTS_BY_CATEGORY_SUCCESS_FAIL,

    CLEAR_ERRORS
} from '../Constrants/ProductConstrants.js'
export const productReducer  = (state = { products : []},action)=>{
    switch(action.type){
        case GET_PRODUCTS_BY_CATEGORY_REQUEST:
            return {
                loading: true,
                products: []
            }
        case GET_PRODUCTS_BY_CATEGORY_SUCCESS:
            return{
                loading: false,
                rows: action.payload.rows,
            }
            case GET_PRODUCTS_BY_CATEGORY_SUCCESS_FAIL:
                return {
                    loading: false,
                    error: action.payload
                }
                case CLEAR_ERRORS:
            return {
                ...state,
                error: null
            }
            default:
            return state
    }
} 
1

There are 1 best solutions below

0
On

Try to get using axios like this

const{ data } = await axios.get(`/api/v1/catproduct/${categoryId_fk}`)