DEV Community

Rafael Teles Vital
Rafael Teles Vital

Posted on

Utilizando "createAsyncThunk" do Redux para fazer chamada async

JÁ PRECISOU INICIALIZAR O ESTADO DO REDUX COM RESULTADO DE UMA API ASYNC?

Pois bem aqui está um exemplo de como funcionar essa chamada async da API, para inicializar o estado no redux.

Primeiramente criamos uma função async, nesse caso chamada de "loadCourse" e depois podemos colocar dentro do "createSlice" na propriedade extraReducers, quando a função criada estiver com o state como "fulfilled" recebemos o retorno no campo action.payload, como segue abaixo.

export const loadCourse = createAsyncThunk(
  'player/load',
  async () => {
    const response = await api.get('/courses/1')

    return response.data
  }
)

export const playerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: { 
  // como se fosse useEffect para carregar
  extraReducers(builder) {
    builder.addCase(loadCourse.fulfilled, (state, action) =>{
      state.course = action.payload
    })
  }
})
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay