0

I'm fetching data from firestore and dispatching an action through redux. Right now it looks like this:

export const mildvalue  = createSlice ({
  name:"mild",
  initialState:{text:"Press to refresh", key:1},
  reducers:{
    shuffleMild:(state, action) => {

    console.log(action.payload)
      
    }
  }
})

And the data coming from the console log and firestore is a key/value pair and looks like this:

{"ref1": "trying text 1", "ref2": "trying text 2", "ref3": "trying text 3", "ref5": "trying text 5"}

What I WANT to do is to put this data as objects in an array so that I can shuffle through them by assigning keys etc to replace the initialState. But I don't understand how I should do this. Please help me

1 Answer 1

2

Ideally you should change your query to Firestore, but you didn't provide your code for that.

Alternatively, you can loop through this payload and create your array with objects like this:

export const mildvalue  = createSlice ({
  name:"mild",
  initialState:{text:"Press to refresh", key:1},
  reducers:{
    shuffleMild:(state, action) => {
      const data = [];
      Object.entries(action.payload).forEach((i) => {
        const key = i[0];
        const value = i[1];
        data.push({[key]: value});
      })
      // do whatever you want with data here
    }
  }
})
Sign up to request clarification or add additional context in comments.

2 Comments

thank you this worked, but how do you mean that I should change my query to Firestore?
It depends on how your data is stored in Firestore. But usually you'd store documents which are each retrieved as an object. When querying all the data with getDocs you can loop through it, add it to an array, then return the array. Like the example in the docs: firebase.google.com/docs/firestore/query-data/…

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.