i got "TypeError: data.map is not a function" and i can't get the data from backend

21 views Asked by At

i'm stuck in this error since two days couldn't get some sleep i don't understand what seems the problem since redux and redux toolkit have migrated to a newer version and i seem lost in the code here is the formSlice.js and the fetcForms action

export const fetchForms = createAsyncThunk('data/fetchAll', async () => {
  const response = await fetch("http://localhost:5000/autoroute/");
  const data = await response.json();
  return data;
});


const initialState = {
  data: [],
  status: 'idle',
  error: null
};
const formSlice = createSlice({
  name: 'data',
  initialState:{},
  extraReducers: (builder) => {
    builder
      .addCase(fetchForms.fulfilled, (state, action) => {
        state.data = action.payload; 
      })
  },
});
//and this is the home component where i'm trying to display data

const dispatch = useDispatch();
    const data = useSelector((state) => state.data); 
    console.log(data)
    useEffect(() => {
      dispatch(fetchForms()); 
    }, [dispatch]);
    
    return (
      <div>
        <h2>Form Data</h2>
//and this where the error occurs
        {data && data.map((form) => (
          <div key={form._id}>
            <p>Type of Accident: {form.accident}</p>
            <p>Route Type: {form.route}</p>
            <p>Lane: {form.lane}</p>
            <p>Number of Fatalities: {form.nbrmort}</p>
            <p>Number of Injuries: {form.nbrblesse}</p>
            {/* Other form details */}
          </div>
        ))}
      </div>
    );
1

There are 1 answers

2
kianoosh kheirani On

It seems like you're encountering an issue with Redux Toolkit and how you're defining your initial state and handling the data in your reducer. Let's take a closer look at your code.

Firstly, in your formSlice, you're defining initialState as an empty object, but then in your extraReducers, you're trying to directly access state.data. This would throw an error because initially, state is an empty object.

To fix this, you should define your initialState with the correct structure. In your case, it should match the structure of the state you're trying to update in your reducer. So, it should look like this: const initialState = { data: [], status: 'idle', error: null }; Secondly, in your useSelector hook, you're accessing state.data, but since you've named your slice as 'data', you should access it like state.data.data.

Here's how you can adjust your useSelector: const data = useSelector((state) => state.data.data);With these changes, your code should work properly. If you still encounter any issues, please let me know!