Reputation: 25
I am trying to render a list of exercises using React Native's FlatList component, and I'm currently unable to successfully edit the name of the exercise. Everything runs smoothly upon the initial render. However, when I try to edit the exercise, the subsequent re-render returns the error undefined is not an object (evaluating 'item.id')
. If I check my local database, the data is successfully edited, but rendering it to the screen is another issue. If I were to dismiss the error display and reload the app, however, the expected changes have been made to the exercise.
I've seen previous posts/responses surrounding this issue, but from what I can tell, I've tried the suggested solutions to no avail.
Here is the component responsible for rendering the FlatList:
function Exercises({ fetchExercises }) {
const dispatch = useDispatch()
const exercises = useSelector(state => state.exercises) // **passed to data prop**
useEffect(() => {
dispatch(fetchExercises())
}, [dispatch])
<FlatList
data={exercises}
keyExtractor={item => item.id.toString()}
renderItem={({ item }) => {
return <ExerciseListItem item={item} />
}}
/>
Below is the action I'm dispatching in the useEffect:
export const editExercise = (id, changes) => dispatch => {
dispatch({ type: EXERCISE_START })
axios.put(<endpoint>, { name: changes })
.then(res => {
dispatch({ type: EDIT_EXERCISE_SUCCESS, payload: res.data })
.catch(err => {
dispatch({ type: EDIT_EXERCISE_FAIL, payload: err })
}
}
...and here is my reducer:
const initialState = {
exercises: [],
}
const exercisesReducer = (state = initialState, action) => {
switch (action.type) {
case EDIT_EXERCISE:
return {
...state,
isLoading: false,
exercises: state.exercises.map(exercise=> {
exercise.id === action.payload.id ? action.payload : exercise
}
}
}
}
For what it's worth, I'm able to successfully add a new exercise to the list. Not sure if that would make a difference, but it's worth mentioning. Also, here is a similar question that someone asked about a year ago with what would appear to be the solution to my issue, but I'm still not getting the expected results.
Any help would be greatly appreciated!
Upvotes: 0
Views: 147
Reputation: 8936
I think the issue is that you're not returning anything in your map
which is leading to this error.
exercises: state.exercises.map(exercise=> {
return exercise.id === action.payload.id ? action.payload : exercise
}
Upvotes: 1