Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

309
Visualizações
Redux toolkit axios api is not getting called

Can someone please help me to find what exact problem is with below code, as i am new in redux.

  • API is not called
  • data is not coming to state products[] array

product-slice.js

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

const initialState = {<br/>
  products: [],<br/>
  sample: "Hello World",<br/>
};<br/>

<br/>
const productSlice = createSlice({<br/>
  name: "productSlice",<br/>
  initialState,<br/>
  reducers: {<br/>
    getProducts(state, action) {<br/>
      const p = action.payload;<br/>
      console.log(p);<br/>
    },<br/>
  },<br/>
  extraReducers: (builder) => {<br/>
    builder.addCase(fetchProductData.fulfilled, (state, action) => {<br/>
      state.products.push(action.payload);<br/>
    });<br/>
  },<br/>
});<br/>

export const fetchProductData = createAsyncThunk(<br/>
  "products/fetchProducts",<br/>
  async (_, thunkAPI) => {<br/>
    try {<br/>
      const response = await axios.get("http://localhost:8080/products");<br/>
      return await response.data;<br/>
    } catch (error) {<br/>
      return error;<br/>
    }<br/>
  }<br/>
);<br/>

export const productActions = productSlice.actions;<br/>

export default productSlice;<br/>

ProductList.js(Component)<br/>

const ProductList = (props) => {<br/>
  const history = useHistory();<br/>
  const hello = useSelector((state) => state.products.sample);<br/>
  const dispatch = useDispatch();<br/>
<br/>
  useEffect(() => {<br/>
    dispatch(fetchProductData);<br/>
  }, [dispatch]);<br/>
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You should call an action as a function inside dispatch() like dispatch(fetchProductData()) and implement redux/toolkit with thunk middleware like below (example):

as you can see in reduxToolkitCreateAsyncThunk

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
  name: 'users',
  initialState: { entities: [], loading: 'idle' },
  reducers: {
    // standard reducer logic, with auto-generated action types per reducer
  },
  extraReducers: (builder) => {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(fetchUserById.fulfilled, (state, action) => {
      // Add user to the state array
      state.entities.push(action.payload)
    })
  },
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda