Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to call api on load using hooks in react

function User() {
  const [firstName, setFirstName] = React.useState(null);
  const [lastName, setLastName] = React.useState(null);
  
  React.useEffect(() => {
    fetch('https://randomuser.me/api/')
      .then(results => results.json())
      .then(data => {
        const {name} = data.results[0];
        setFirstName(name.first);
        setLastName(name.last);
      });
  }, []); // <-- Have to pass in [] here!

  return (
    <div>
      Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`}
    </div>
  );
}

ReactDOM.render(<User />, document.querySelector('#app'));
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to prevent render in react 
Javascript :: array push 
Javascript :: how to set dropdown value in textbox using jquery 
Javascript :: vue 3 $refs 
Javascript :: js not not 
Javascript :: objeto con método javascript 
Javascript :: How to Check for an Empty String in JavaScript by String Comparison 
Javascript :: hover on child from parent mui react 
Javascript :: expressjs allow cors for all hosts and ports 
Javascript :: display text on button click react 
Javascript :: res.write in node js 
Javascript :: moyenne javascript 
Javascript :: ~~ in javascript 
Javascript :: slice() in js 
Javascript :: how to use cordova screen shot 
Javascript :: daysjs 
Javascript :: reactt split a value and sepate 
Javascript :: responsive font size react native 
Javascript :: change bg-color all class 
Javascript :: what is javascript used for 
Javascript :: react native shadow maker 
Javascript :: Find All Less Than Equal To In MongoDB 
Javascript :: array.splice 
Javascript :: how to put submit type of input element in a queryselector in javascript 
Javascript :: js check if object key exists 
Javascript :: dropzone upload on one file 
Javascript :: repeating countdown timer javascript 
Javascript :: flask sqlalchemy json 
Javascript :: vue for start at index 
Javascript :: elixir guards 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =