J
J
JekaHC2022-03-31 02:03:01
JavaScript
JekaHC, 2022-03-31 02:03:01

How to properly get data from JSON file in React?

Due to not knowing React well enough, I ran into a problem. There is a JSON
file . There are React components . Link to the entire repository. At the moment, in the Main.jsx file, I am trying to extract the data from the JSON file "products.json" and carry out further manipulations with them (Product.jsx; Products.jsx). The end result is "Nothing found" ( Condition in Products.jsx) Question - what is the problem, why can't I display the data? Photo Main.jsx Photo Product.jsx Photo Products.jsx







6244e134a5205027649588.png


6244e15400afb444906743.png


6244e175a2e4f239803380.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HealSpirit, 2022-03-31
@JekaHC

import React from "react";
import { Products } from "../Products";

class Main extends React.Component {
  state = {
    products: [],
  };

  componentDidMount() {
    fetch("./products.json")
      .then((responce) => responce.json())
      .then((data) => this.setState({ products: Object.values(data) }));
  }

  render() {
    const { products } = this.state;

    return (
      <main className="container content">
        <Products products={products} />
      </main>
    );
  }
}

export { Main };

Strange json, to be honest. Usually, such things are stored in an array near some field in JSON.
It would also be necessary to remove the array element 200, which turned out after the transformation "response_code": 200 -> 200,
remove 2 warnings in the console:
1) the initialization of the application has changed a little after switching to version 18 of the react
2) if you print out the components from the array, each element needs add attribute/property key. You need to use some unique value (for example, id). If it is not there, at least use the index of the current iteration

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question