0

I have axios making a get request to fetch a request a list of vessels and their information, i am trying to use redux slice, and populate the data using dispute, however the state is always empty dispute not having any errors enter image description here

the 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);
  }
};

the HomeScreen.js :

import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { fetchVessels } from "../../../features/vesselSlice";

export const api = () => {
  axios
    .get("http://127.0.0.1:8000/api/vessels/info")
    .then((data) => console.log(data.data))
    .catch((error) => console.log(error));
};

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;
newprogrammer12
  • 231
  • 1
  • 10

1 Answers1

1

You receive dispatch this way. It is not being received from any middleware.

export const fetchVessels = async (dispatch) =>{}

If you want to continue using your approach, call function this way

 useEffect(() => {
    fetchVessels()(dispatch);
  }, [dispatch]);

Api function error

export const api = async () => {
  try {
    const res = await axios.get("http://127.0.0.1:8000/api/vessels/info");
    return res.data;
  } catch (error) {
    console.log(error);
  }
};
export const fetchVessels = () => async (dispatch) => {
  try {
    await api()
         .then((data) => dispatch(getVessels(data)));
  } catch (e) {
    return console.error(e.message);
  }
};

Inder
  • 1,711
  • 1
  • 3
  • 9