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

311
Visualizações
TypeError: Cannot read properties of undefined (reading 'name') - React , redux-toolkit

I fetch data from API by using react-redux Toolkit. Want to display default city weather datas when page render but it gives an error

TypeError: Cannot read properties of undefined (reading 'name')

Output - > Empty Array from index.js than API output from WeatherSlice.js

export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`http://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=${selectedCity}&days=10&aqi=no&alerts=no
`)
return res.data 

});

<Typography className="label" variant="h5" sx={{pb:5}} component="div">
                 {getCity.location.name} // GivesTypeError
    </Typography>

Home component

const getCity  = useSelector((state) => state.weather.item);
useEffect(() => {
    dispatch(fetchDefault(selectedCity))
    console.log()

}, [dispatch])

App.js

<Switch>
    <Route path="/about" component={About} >
      <About />
    </Route>
    <Route path="/" component={Home}>
      <Home />
    </Route>
  </Switch>

Store.js

 export const store = configureStore({
  reducer: {
    weather : weatherSlice.reducer,
  },
})

WeatherSlice.js

export const weatherSlice = createSlice({   
name: "weather",
initialState : {
    item : [],
},
reducers:{},
extraReducers:{
    [fetchDefault.fulfilled]: (state , action) => {
       
        state.item = action.payload;
        console.log(state.item)
    },
    [fetchDefault.pending]: (state , action) => {
       
        console.log("sadsad")
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I checked the api you used (https://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=Istanbul&days=10&aqi=no&alerts=no) to see what it returns.

Response data is an object with fields: location, current and forecast.

So at first, I think the initial state for "item" should not be an empty array because api does not returns an array instead it should be undefined or empty object.

Then, the main reason that the TypeError exists is you can not retrieve data or can not fill the item in the state. You should check the data that returns from the api. Can you successfully retrieve the data and fill the state with it?

Reason of TypeError: If you have an empty array or empty object and try to access a field through this element (like item.location) it will not show an error, but if you try to access a field of a field (like item.location.name) the TypeError occurs.

Also checking the object before component will be safer. Like:

// can be undefined comparison or getCity.length > 0 etc
{getCity !== undefined && (
        <Typography className="label" variant="h5" sx={{pb:5}} component="div">
              {getCity.location.name} // GivesTypeError
        </Typography>
)}
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