0

I am new in redux and redux-toolkit. I am trying to get data from api. I get error and can not receive data from api. I am using redux-toolkit library.

This is my App.js:

function App() {

  const companies = useSelector(state => state.companyList);
console.log(companies)
  return (
    <div className="App">
      <header className="App-header">
        {companies.map(company => {
          return(
            <h1>{company.name}</h1>
          )
        })}
        <h1>hello</h1>

      </header>
    </div>
  );
}

export default App;

This is createSlice.js

const getCompanies = axios.get(
  "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
).then((response) => {
    console.log(response.data)
    return response.data;
}).catch((ex) => {
    console.log(ex)
})


export const companySlice = createSlice({
  name: "companyList",
  initialState: {value: getCompanies},
  reducers: {
    addCompnay: (state, action) => {},
  },
});

export default companySlice.reducer;

Here is store.js

import { configureStore } from "@reduxjs/toolkit";
import companyReducer from "./features/companySlice/compnayList";

export const store = configureStore({
    reducer:{
        companyList: companyReducer, 
    }
})

In the browser, I receive this error: enter image description here

4
  • Maybe you wanted this const companies = useSelector(state => state.companyList.value);? Commented Jun 15, 2022 at 13:21
  • 1
    Your approach is wrong. Look at createAsyncThunk or createApi examples from the official docs. Commented Jun 15, 2022 at 13:24
  • 1
    You are missing several steps here. Please follow the official Redux tutorial which will guide you thtough all of this: redux.js.org/tutorials/essentials/part-1-overview-concepts Commented Jun 15, 2022 at 13:31
  • Thank you for your response. I think I should read the redux official site in deep. Commented Jun 16, 2022 at 5:32

3 Answers 3

8

You are making a lot of mistakes here so be sure to check out some tutorials and docs: https://redux-toolkit.js.org/tutorials/quick-start

You need to use createAsyncThunk and handle the response in extraReducers: https://redux-toolkit.js.org/rtk-query/usage/migrating-to-rtk-query#implementation-using-createslice--createasyncthunk

In companySlice:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

export const getCompanies = createAsyncThunk(
  "companyList/getCompanies", 
  async () => {
    try {
      const response = await axios.get(
        "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
      );
      return response.data;
    } catch (error) {
      console.error(error);
    }
});

const companySlice = createSlice({
  name: "companyList",
  initialState: {
    company: {},
    isLoading: false,
    hasError: false
  },
  extraReducers: (builder) => {
    builder
      .addCase(getCompanies.pending, (state, action) => {
      state.isLoading = true;
      state.hasError = false;
    })
      .addCase(getCompanies.fulfilled, (state, action) => {
        state.company = action.payload;
        state.isLoading = false;
        state.hasError = false
      })
      .addCase(getCompanies.rejected, (state, action) => {
        state.hasError = true
        state.isLoading = false;
      })
  }
});

// Selectors
export const selectCompanies = state => state.companyList.company;
export const selectLoadingState = state => state.companyList.isLoading;
export const selectErrorState = state => state.companyList.hasError;

export default companySlice.reducer;

Then you import selectCompanies wherever you want to use it and access it with useSelector.

In App.js:

import { useSelector } from "react-redux";

import { selectCompanies } from "WHEREEVER selectCompanies IS EXPORTED FROM";

function App() {
  // Company list state
  const companies = useSelector(selectCompanies);

  // Rest of the code
  .....
  .....
  .....
  .....
}

export default App;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your nice response. I tried your code in my project, so now how to access the data in app.js. Can you please let me know?
Just like you were using useSelector to access the data state, import the selectCompanies from companySlice into your App.js and use useSelector to access it. I'll update the answer to cover that part as well. Please upvote and accept the answer as the solution if it fixed your issue.
0

I used addMatcher instead of addCase to get it working. As described here: https://redux-toolkit.js.org/api/createAsyncThunk

Comments

0

Finally, you should do the App.js file as follows

In App.js:

import { useSelector } from "react-redux";

import { selectCompanies } from "WHEREEVER selectCompanies IS EXPORTED FROM";

function App() {
  const dispatch = useDispatch()
  // Company list state
  const companies = useSelector(selectCompanies);

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


  // Rest of the code
  .....
  .....
  .....
  .....
}

export default App;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.