Search code examples
reactjsreact-reduxaxiosreact-hooksredux-thunk

Redux useSelect doesn't get all data as expected


I'm trying to print out data from my database. It's doing it all well by using hooks and without it so this time I tried to use redux and hooks to implement CRUD. But thats return an undefined every render. so I called the payload and it's an array of objects. I'm using redux, middleware Thunk and hooks. please can someone guide me to fix the issue.

here is the code bellow :

Component.jsx

import { retrieveCars } from '../action/cars.action'
    
     const cars = useSelector(state => state.cars);
        const dispatch = useDispatch();
      
        useEffect(() => {
          dispatch(retrieveCars());
          


        });
 <tbody>
                    {cars &&
                      cars.map((data) =>
                        <tr key={data.idCars}>
                       
                        <th scope="row">{data.idCars}</th>  
                      
                      <td>{data.carName}</td>
                      <td>{data.carModel}</td>
                      <td>
                      <Link to={"/classement/update/" + data.idCars}
                        className="btn btn-info"
                        >
                        Edit
                       </Link>
                
                      <button  className="btn btn-danger" onClick={() => deleteC(data.idCars)}>
                        Remove
                      </button>
                        </td> 
                     
                      
                     
                      </tr>
                    )
                    }
                      
                
                  </tbody>
        **cars.action.js**
export const retrieveCars = () => async (dispatch) => {
    try {
      const res = await DataService.getAll();
  
      dispatch({
        type: RETRIEVE_CARS,
        payload: res.data,
      });
    } catch (err) {
      console.log(err);
    }
  };

Car Reducer:

const initialState = [];
  
  function carReducer(cars = initialState, action) {

    const { type, payload } = action;
  
    switch (type) {    
      case RETRIEVE_CARS:


           return payload;
   default:
        return cars;
    }

Store.js

import rootReducer from '../reducers/carReducer';
const initialState = {};

const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

enter image description here


Solution

  • I saw you are using carReducer for rootReducer. And carReducer only has state is an array. So state is an empty array and state.cars is undefined.

    Just update like this to get cars:

    const cars = useSelector(state => state);