Search code examples
reactjsreact-nativegoogle-cloud-firestorereduxredux-firestore

Turning data from firestore into array (react-native)


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


Solution

  • 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
        }
      }
    })