Home > front end >  Redux state is empty
Redux state is empty

Time:05-22

I am following a redux example to create a slice in react-redux, in my console i have no errors and the state has my vessels but it's just empty and doesnt have any data from my axios api call, my backend is running and the api call is working fine.

vesselSlice :

import { createSlice } from "@reduxjs/toolkit";
import { api } from "../components/pages/screens/HomeScreen";
const vesselSlice = createSlice({
  name: "vessels",
  initialState: {
    vessels: [],
  },
  reducers: {
    getVessels: (state, action) => {
      state.vessels = action.payload;
    },
  },
});
export const vesselReducer = vesselSlice.reducer;
const { getVessels } = vesselSlice.actions;

export const fetchVessels = () => async (dispatch) => {
  try {
    await api
      .get("/vessels")
      .then((response) => dispatch(getVessels(response.data)));
  } catch (e) {
    return console.error(e.message);
  }
};

HomeScreen :

import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  return (
    <div>
      Fleet vessels :
      <div className="fleet-vessels-info">
        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}
      </div>
    </div>
  );
}

export default HomeScreen;

CodePudding user response:

You have to actually call the function fetchVessels. In this simple example, I would do it using useEffect:

import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice, fetchVessels } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  const dispatch = useDispatch();

  // This part:
  useEffect(() => {
    fetchVessels(dispatch);
  }, [dispatch]);

  return (
    <div>
      Fleet vessels :
      <div className="fleet-vessels-info">
        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}
      </div>
    </div>
  );
}

export default HomeScreen;
  • Related