Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
How do I connect to my state by ID params in Redux Toolkit when the data is an object not an array?

Take a look at my Slice below

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const KEY = process.env.REACT_APP_API_KEY
const BASE_URL = process.env.REACT_APP_BASE_URL
const API = `${BASE_URL}/countrymap`

const initialState = {
  mapdata:[],
  status: 'idle',  
  error:null
}

export const fetchMapData = createAsyncThunk(
  'mapdata/fetchMapData', 
  async (id) => { 
    try {
      const response = await axios.get(
        API,
        {
          headers: {
            'Content-Type': 'application/json',
            'X-API-KEY': KEY,
          },
          params: {
            titleId: id,
          }
        }
      )

      return response.data.Item;
    } catch (error) {
      console.error('API call error:', error.message);
    }
  }
)

const mapSlice = createSlice({
  name: 'mapdata',
  initialState,
  reducers:{
  },
  extraReducers(builder) {
    builder
      .addCase(fetchMapData.fulfilled, (state, action) => {
        state.status = 'succeeded'
        //This attempt to make it an array failed with the error
        //  that the state is not iterable
        state.mapdata = [action.payload, ...state] 
        console.log("map payload: ", state.mapdata);
      })
  }
})

// SELECTORS
// This works for an array, but the data is originally coming 
//  in as an object instead
export const allMapData = (state, id) => state.mapdata.mapdata.find(item => item.title_id === id); 

export default mapSlice.reducer

for reference, look at these two console logs from two different API calls to two different endpoints from two different slices . Except Media is coming back as an array, and map is an object

enter image description here

I need to either, turn the state.mapdata into an Object to I can use the selector the way it is or re-code the selector so that it doesn't use the .find() function because that's an array function. But either way, it needs to compare the titleId in the data to the id in the params

Sorry for not providing workable code. I would but there is an insane amount of dependencies here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should use

state.mapdata = [action.payload, ...state.mapdata] 

instead of

state.mapdata = [action.payload, ...state] 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda