Using the explicit documentations , I structured a 'home' reducer using the createSlice() method provided by the redux toolkit library and then used an async API call to get offers to store to the redux state using the createAsyncThunk method. Here is the following code for the reducer
import {createAsyncThunk, createSlice, PayloadAction} from '@reduxjs/toolkit';
import testService from '../../api/services/test.service';
const getOffers = createAsyncThunk(
'home/getOffersStatus', //I tried changing the type string but to no avail
async (thunkAPI) => {
const res = await testService.getOffers();
return res.data;
},
);
const home = createSlice({
name: 'home',
initialState: {
offers: {
loader: false,
data: null,
err: null,
},
},
reducers: {},
extraReducers: builder => {
builder.addCase(getOffers.fulfilled, (state, action) => {
state.offers.data = action.payload
});
},
});
export default home.reducer;
Next I called the method getOffers()
inside home.js
. As shown below:
import React, {useEffect} from 'react';
import {ScrollView, Text, View} from 'react-native';
import {Button, Icon} from 'react-native-elements';
import {useTheme, withTheme} from 'react-native-paper';
import {useDispatch} from 'react-redux';
import {GlobalStyles} from '../../constants/globalStyles';
const Home = ({navigation}) => {
const theme = useTheme();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getOffers()); // <------- Problem Occurs Here
}, []);
return (
<ScrollView
style={GlobalStyles.bgScrollView}
contentContainerStyle={(GlobalStyles.flex1, GlobalStyles.flexGrow)}>
<View
style={{flex: 1, margin: 40, marginTop: '30%', alignItems: 'center'}}>
<Text textAlign="center">{'This is Home Screen'}</Text>
<Button
buttonStyle={GlobalStyles.buttonPrimary}
title="Redeem Offer Screen >"
onPress={() => {
navigation.push('Redeem Offer');
}}
/>
</View>
</ScrollView>
);
};
export default withTheme(Home);
Now when I call the dispatch I get the following error:
Uncaught ReferenceError: getOffers is not defined at home.js:13
What am I doing wrong?
The problem is caused by getOffers
function is not exported from home reducer file and consequently not imported in home.js
component.
You should export getOffers
from your home reducer like:
export const getOffers = createAsyncThunk(
and then you should import it in your home.js
component like:
import { getOffers } from 'path-to-your-home-reducer-js'; // the relative path to reducer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.