0

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
Anoop K George
  • 1,605
  • 12
  • 40
  • 3
    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. https://stackoverflow.com/a/55683451/7956790 – Kox May 18 '20 at 15:45
  • 1
    Thanks, I hope I have to study about aync actions – Anoop K George May 18 '20 at 15:53

1 Answers1

1

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

case 'FETCH':
        return { post:action.payload}
vaycs
  • 33
  • 5
  • 1
    The curly brackets around that line actually are just a code block. They aren't needed in this example because there are no variable declarations in the case, but they also aren't the source of the issue (or even an issue at all) – Zachary Haber May 18 '20 at 16:02