0
votes

I am using React JS with Redux, I am trying to fetch data from API but encountered two error.

ACTION CREATOR: The below code supposed to get API data and return it. I don't know how to return fetched data

import axios from 'axios';
const fetchlist = (id)=>{    
    const post = axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`).then(response=>response.data)

    return{

        type:'FETCH',
        payload:post.data
    }
}

export default fetchlist

REDUCER FUNCTION the below code is to update the post state but gets error Block is redundant no-lone-blocks

const post=(state={post:{}},action)=>{
switch(action.type){
    case 'FETCH':{    // ERROR OCCURES IN THIS LINE
        return { post:action.payload}
    };
    default: return state
}}

export default post
1
First of all, your fetchlist action creator performs an async operation so you need to prepend async (id) => { and await axios.get(...). Secondly, you need something like redux-thunk to hook asynchronicity into Redux flow. stackoverflow.com/a/55683451/7956790 - Kox
Thanks, I hope I have to study about aync actions - Anoop K George

1 Answers

1
votes

In switch statement remove the curly brackets before return it should be :

case 'FETCH':
        return { post:action.payload}