I'm trying to fetch data in redux and return a part of them, not all of it, but Typescript tells me that "Property 'xxx' does not exist on type 'string[]'". I tried to see it it has to do with the interface or the initialState but cannot find a solid answer.
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import { useAppDispatch } from './hooks';
export interface MealState {
meal: string[],
input: string,
favorites: string[],
categories: string[],
}
const initialState: MealState = {
meal: [],
input: '',
favorites: [],
categories: [],
};
const mealReducer = createSlice({
name: 'meal',
initialState,
reducers: {
// ADD INPUT
addInput: (state, action: PayloadAction<string>) => {
state.input = action.payload
},
},
extraReducers: (builder) => {
builder.addCase(getMeal.fulfilled, (state, action) => {
state.meal = action.payload;
});
}
});
// ----------------------------------------------------------------------
export default mealReducer.reducer
// Actions
export const {
addInput,
addFavorites,
} = mealReducer.actions;
export const getMeal = createAsyncThunk(
'meal/getMeal',
async (search: string) => {
const response = await axios.get<string[]>(`https://www.themealdb.com/api/json/v1/1/search.php?s=${search}`);
return response.data.meals; // <== this create the problem, I can only return response.data
}
);
I can work with response.data, but then the problem is the same when I use
const list = useAppSelector((state: RootState) => state.meal.meal.meals)
since meals does not exist in the first place i will get "Property 'meals' does not exist on type 'string[]'"
CodePudding user response:
the return
value of your function getMeal
is what you will get as value for the meal
attribute of your state
, and since
meal: string[]
the getMeal
function should return data of type string[]
which is not the case here according to the error you got
what I suggest is :
- console.log and understand better what you are getting as response from the request
- create const myMeal from the response
- return it
async (search: string) => {
const response = await axios.get<any>(`https://www.themealdb.com/api/json/v1/1/search.php?s=${search}`);
console.log(response.data);
const myMeal: string[] = // I don't know how your response.data looks like but myMeal should be of type string[]
return myMeal;
}