'React Native with Redux Toolkit - Dispatch function produces TypeError: action is undefined
Thank you in advance for your time!
As the title describes, I am trying to fetch data from a json file asynchronously and store it in the state with Redux's latest Toolkit version. Unfortunately, running
dispatch(getCities())
Produces Uncaught TypeError: action is undefined
I would appreciate any insight on this! Below goes the code:
STORE.JS
import { configureStore } from "@reduxjs/toolkit";
import citiesReducer from "../features/cities/citiesslice";
const store = configureStore({
reducer:{
cities: citiesReducer
}
})
export default store;
CITIESSLICE.JS
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
const API_URL = 'https://warply.s3.amazonaws.com/data/test_pois.json'
export const getCities = createAsyncThunk(
"cities/getCities",
async (dispatch, getState)=>{
return await fetch('https://warply.s3.amazonaws.com/data/test_pois.json')
.then(
console.log('test')
)
}
);
const citiesSlice = createSlice({
name: "city",
initialState: {
cities: [],
loading: 'idle'
},
extraReducers:{
[getCities.pending]: (state,action)=>{
state.loading = "pending"
},
[getCities.fulfilled]: (state, action)=>{
state.loading = "succeded"
state.cities = action.payload
},
[getCities.rejected]: (state, action)=>{
state.loading = "failed"
}
},
})
export default citiesSlice.reducer;
MAPLIST.JS
import React, { useEffect } from 'react';
import { SafeAreaView, StyleSheet, Image, Text, View } from 'react-native';
import getCities from '../features/cities/citiesslice';
import { useDispatch, useSelector } from 'react-redux';
function MapList(props) {
const dispatch = useDispatch();
const {cities}= useSelector(state => state.cities)
useEffect(()=>{
dispatch(getCities())
},[])
return (
<SafeAreaView style={styles.container}>
<View style={styles.topnav}>
<Image source={require('../assets/warply_w.png')} style={styles.logo}/>
</View>
{cities && cities.map((cities, i)=> <Text key={i}>test</Text>)}
</SafeAreaView>
);
Styles not included in the above excerpt as likely not associated with issue
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
