0

I'm new with react and redux and I was checking a shopping cart app, what if I want to fetch these dummy objects from an external api. I can fetch apis in react but redux makes it a little confusing for me.

productsReducer.js

const INIT_PRODUCTS = [
    {id:1, title: 'Watch', description: 'Lorem Ipsum', price: 80, img:''},
    {id:2, title: 'Watch', description: 'Lorem Ipsum', price: 50, img:''},
    {id:3, title: 'Watch', description: 'Lorem Ipsum', price: 35, img:''}
];
export default function productsReducer(state=INIT_PRODUCTS, action={}) {

    function findProductIndex(products, id) {
        return products.findIndex((p) => p.id === id)
    }

    return state;
}
1

1 Answer 1

2

when you use fetch API you do asynchronously action ( call to server is usualy async ) . redux dont support async actions by defualt. so you need to use middleware called 'thunk' or 'redux-saga' ( thunk is easier ) this middleware give you the ability to use redux with async actions.

how thunk work? you create an action creator that return a function instead of acrion creator that return an object. and you pass to this returned function the dispatch function from the store. this give the returned function the ability to call the dispatch asynchronously- as a callback

this is the best guide on this subject

thunk for dummy's

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.