fanjiooJr
fanjiooJr

Reputation: 329

REDUX - how to store ARRAY id's when i do a dispatch loop?

I need to save the ID's that I am receiving when fetching in a loop in the store but I am not realizing how to iterate the object

This is my action's


export function uploadImage(files) {
    return function async(dispatch) {
        const myHeaders = new Headers();
        myHeaders.append("Authorization", `Token ${localStorage.getItem('***')}`)
        for(let i = 0; i < files.length;  i++) {
            const formdata = new FormData();
            formdata?.append("image", files[i], files[i].name);
            
            fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
                'method': "POST",
                'headers': myHeaders,
                'body': formdata,
                'redirect': 'follow'
            })
                .then(resp => resp.json())
                .then(json => dispatch(activeImage(json.id)))
        }
    }
}

export const activeImage = ( id ) => ({
    type: "PUSH_ID_IMAGE",
    payload: id
});


My reducer:


case "PUSH_ID_IMAGE":
            return{
                ...state,
                images: [...action.payload]
            }
        

Upvotes: 0

Views: 215

Answers (1)

Shaded
Shaded

Reputation: 158

Redux actions don't support async actions by defualt, you could try using redux-thunk

It allows you to return a function as an action and gives you access to dispatch and getState so you can dispatch events to your reducer from within the function as well as being able to retrieve the state

After installing redux-thunk you could write something like this as your action:

const uploadImage = files => {
  return async (dispatch, getState) => {
    // ... your proccessing / loop here
    
    // ... inside the loop
    const response = await fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
        'method': "POST",
        'headers': myHeaders,
        'body': formdata,
        'redirect': 'follow'
    })
      .then(resp => resp.json())
     
    dispatch({
      type: "PUSH_ID_IMAGE",
      payload: response 
    })  // send the data returned from "resp.json"
  }
}

Upvotes: 1

Related Questions