Answer the question
In order to leave comments, you need to log in
How to render in react on first load?
I just started learning React, I didn't understand one important thing. We usually take data for components in the form of json, which we easily get into a variable after ajax requests, but I just can’t google how to get json for the component on the first page load, for example, if the backend is in php, then echo json_encode() will still display first on the page and then it will be picked up by the react, tell me how to organize the output of data from the server, so that the react already knows what data it should work with, maybe echo "script var data ={test: 'yes'} /script" or is this a perversion? thanks in advance
Answer the question
In order to leave comments, you need to log in
To do this, React has a useEffect hook ( https://ru.reactjs.org/docs/hooks-effect.html )
To get JSON on the first page load, you need to import the useEffect hook. This hook (hook = function) has 2 required parameters - the first is a function (callback) and the second is an array of dependencies (if you leave it empty, the hook will work only once, as you need in the task).
I offer a code example below:
Using fetch, we make a get request for data, the server will return the data and after that we get json from them using the appropriate method and then output to the console
import React, { useEffect } from 'react';
const Page = () => {
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
}, []);
export default Page;
Google useEffect, or if without componentDidMount hooks or something like that)) component life cycle in general
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question