2

I am trying redux-thunk for the first time Hence working on a simple project the thunk uses the API and displays the data on the screen but the API is returning a JSON object ,to display the titles on the screen I need to use the .map() function to map through the object, but the object doesn't allow us to use map() function so I need to convert the JSON data to an array and the use .map() function to achieve the desired result but I don't know how to convert the JSON data to an array I tried different approaches to deal with this but nothing seems to work for me Here is what I need

const codeReturnedFromJSONRequest ={data:{0:somedata}} //example JOSN data 

what I want my code to look like :

const requiredData=[{data:{0:somedata}}] //I want the required data to be an array so that I can use .map()

If you want my actual code here it is

 //ApiSlice

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const getPosts = createAsyncThunk("posts/getPosts", async () => {
  return fetch("https://api.jikan.moe/v4/anime?q=naruto&sfw").then((response) =>
    response.json()
  );
});
const postSlice = createSlice({
  name: "posts",
  initialState: {
    posts: [],
    loading: false,
  },
  extraReducers: {
    [getPosts.pending]: (state, action) => {
      state.loading = true;
    },
    [getPosts.fulfilled]: (state, action) => {
      state.loading = false;
      state.posts = action.payload;
    },
    [getPosts.rejected]: (state, action) => {
      state.loading = false;
    },
  },
});

export default postSlice.reducer
 //store

import { configureStore } from "@reduxjs/toolkit";
import postReducer from "./anime";

export const store =configureStore({
  reducer: {
    post:postReducer
  }
}) 
//Api data

  import React from "react";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getPosts } from "../store/anime";

function Apidata() {
  const { posts, loading } = useSelector((state) => state.post);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getPosts());
  }, []);
  console.log(posts.data)
  return (
    <div>
      {posts.map((item) => (
        <h2>{item.data}</h2>
      ))}
    </div>
  );
}

export default Apidata;

  // App.js
 import { Fragment, useState } from "react";
  import Apidata from "./components/Apidata";
  function App() {
    return (
      <Fragment>
        <Apidata/>
      </Fragment>
    )
  }

  export default App;
4
  • 2
    what does the response look like if there is more than one returned? {data:{0:blah, 1:foo}} ? Commented Sep 23, 2022 at 13:41
  • 1
    Keep in mind that JSON is an object, so you can't have [{data:{0:somedata}}]. If you want an array inside a JSON, you will need something like {array_data: [{data:{0:somedata}}]} Commented Sep 23, 2022 at 13:46
  • yeah I tried the second approach i made something like in the place of post:[] I added something like post:[data:{}] and tried to puch JSON inside post.data but I was getting an error saying Commented Sep 23, 2022 at 14:00
  • react_devtools_backend.js:4026 A non-serializable value was detected in an action, in the path: payload.0. Value: Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Object Commented Sep 23, 2022 at 14:00

2 Answers 2

1

if you want create an array just wrap the response.json() in an array like that:

     export const getPosts = createAsyncThunk("posts/getPosts", async () => {
      return fetch("https://api.jikan.moe/v4/anime?q=naruto&sfw")
.then(response=>response.json())
.then((response) =>[response]
      );
    });

BUT I don't think it is a best practice. Ask to whom create the backend and get explanations!. Hope the best for you, Mauro

Sign up to request clarification or add additional context in comments.

3 Comments

i tried but now i am getting an error saying
react_devtools_backend.js:4026 A non-serializable value was detected in an action, in the path: payload.0. Value: Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Object
sorry I think is because I forget a second .then(). I updatet the code above. .then(response=>response.json()) .then((response) =>[response]
0

This peace of code resolved my issue

const myObj = {0 : {mal_id: 20, url: 'https://myanimelist.net/anime/20/Naruto', images: 'test', trailer: 'test', approved: true}, 1: {mal_id: 20, url: 'https://myanimelist.net/anime/20/Naruto', images: 'test', trailer: 'test', approved: true}};

const myArr = [];

for (const key in myObj) {
    const arrObj = myObj[key];
  arrObj['id'] = key;
    myArr.push(arrObj)
}

console.log(myArr);

Click here to see the reddit post:

Solution reddit link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.