简体   繁体   中英

Redux/Thunk - async fetch function issues

So i've been practicing on a project of mine where i have a async getItems function in react component named Sheet . It works just fine since i logged the result in console. However when i try to apply redux/thunk way to fetch items from the same API, my new function doesnt even trigger. Tried console.logging the first line of it and nothing happens. Here is hwo they look.

Simple and working one:

const getItems = async (date) =>{
    let request = {}
    try {
        let response = await fetch(`${apiURL}/${date}`, request);
        let data = await response.json();
        console.log(data);
        setItems(data);

    } catch (error){
        console.log("Error fetching data")
    }  
}

The one that im trying to implement instead of the old one, this one doesnt work/trigger:

const fetchItems = () => async dispatch =>{
    console.log("Entered fetch items func");
    let request = {};
    let response = await timesheetApi.get(`/17-3-2021`);
    // TRIED USING FETCH INSTEAD AS WELL, NO RESULT AS WELL:
    // let response = await fetch(`http://localhost:44377/${date}`, request);
    // let data = await response.json();
    console.log(response); 
    dispatch({ type: 'FETCH_ITEMS', payload: response })
}

Both first one and the one that isnt working im trying to call in useEffect of Sheet component. First triggers and gets the array of results , but when i comment it out and put the second one in the same place - it doesnt even trigger (cant debug).

Can someone tell me what im doing wrong by this code?

PS setup from index.js

import thunk from 'redux-thunk'
const store = createStore(reducer, applyMiddleware(thunk));

Axios setup in api folder > timesheetApi.js (But i tried using fetch as well, same (no) result"

import axios from 'axios';
export default axios.create({
    baseURL: 'http://localhost:44377',
});

Reducer.js

function reducer (state = initialStore, action)  {

    switch (action.type) {

        case actionTypes.TRIGGER_MODAL:
                console.log("Triggered loading");
                return { ...state, showModal: !state.showModal }

        case actionTypes.FETCH_ITEMS:
            console.log("Reducer - FETCH_ITEMS case");
            return state;

Note that im testing/having both functions in Sheet component and useEffect to simplify testing. Also date is hardcoded in the second one out of the same reason.

You are defining fetchItems as a thunk action creator, but inside your useEffect you are just calling it without actually dispatching it.

That is akin to defining an action, but never sending it off to redux.

In your useEffect , you have to dispatch(fetchItems())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM