herropaul
herropaul

Reputation: 31

action.payload is returning undefined when I use createAsyncThunk

I'm new to using Redux/Redux-Toolkit and I've been trying to fetch some data using the createAsyncThunk method that RTK provides to asynchronous methods but I've been running into problems where on 'fullfilled' my payload just returns null.

I was also able to console.log the data I fetched just for test purposes, so I know that I'm able to fetch it.

Im not sure if this is a javascript issue I'm having or a Redux issue, so any help is appreciated!

Heres some snippets of the code I have if anyone is interested in helping!

// searchSlice.js

const fetchRequest = () => {
  return fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        Authorization: 'Basic ' + btoa(client_id + ':' + client_secret),
    },
    body: 'grant_type=client_credentials',
  })
}

// searchSlice.js

export const getArtistByQuery = createAsyncThunk('search/getArtistByQuery', async (query) => {
    await fetchRequest()
        .then((result) => result.json())
        .then((data) => {
          const token = data?.access_token;
          const spotify = new SpotifyWebApi();
    
          spotify.setAccessToken(token);
          spotify.searchArtists(query, {limit: 10})
          .then((data) => {
            return data?.artists?.items
          })
        })
})

// Where I dispatch 
// SearchInput.js

const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(getArtistByQuery(query));
    console.log(artists);
    setQuery("");
  }

  return (
    <Flex textAlign="center" m={5}>
        <form onSubmit={handleSubmit}>
            <FormControl>
                <Input mb={5} type="text" onChange={handleChange} placeholder='Enter artist' size="md"/>
                <Button type="submit">Click Me</Button>
            </FormControl>
        </form>
    </Flex>
  )
}

// createSlice

const artistsSlice = createSlice({
    name: 'artists',
    initialState,
    extraReducers: builder => {
      builder.addCase(getArtistByQuery.pending, state => {
        state.loading = true
      })
      builder.addCase(getArtistByQuery.fulfilled, (state, action) => {
        state.loading = false
        console.log("Payload: " + action.payload)
        state.artists = action.payload
        state.error = ''
      })
      builder.addCase(getArtistByQuery.rejected, (state, action) => {
        state.loading = false
        state.artists = {}
        state.error = action.error.message
      })
    }
    })

// initialState

const initialState = {
    loading: false,
    artists: {},
    error: ''
}

// store.js

export const store = configureStore({
  reducer: {
    artistsSlice: artistReducer,
  },
});

Upvotes: 3

Views: 1072

Answers (1)

Yilmaz
Yilmaz

Reputation: 49391

instead of this

export const getArtistByQuery = 
   createAsyncThunk('search/getArtistByQuery', async (query) => {
      await fetchRequest().then

should be this

export const getArtistByQuery = 
   createAsyncThunk('search/getArtistByQuery', async (query) => {
      return await fetchRequest().then()

Upvotes: 2

Related Questions