Home > Back-end >  Using State in React Function
Using State in React Function

Time:01-11

I have been working on the backend and trying to learn React. So, sorry if it is a stupid question. I used the fetch component for API calls in my component with React Functions.

import React, {useState} from "react";
import { Row } from "react-bootstrap";
import * as Constants from '../Constants';
import './index.css';


function ActivitySuggestions(){
 
 var items = null;
 React.useEffect(() => {
    const url = "https://www.boredapi.com/api/activity";
    fetch(url)
      .then((response) => response.json())
     .then((json) => (items = json))
      .catch((error) => console.log(error));
  }, []);


  return(
    <div>items</div>
  );
}

export default ActivitySuggestions

But upon execution, I am getting the string 'text', or whatsoever the text I am providing inside the div, rendered on the browser. Please help me to understand where I am going wrong.

CodePudding user response:

There are a couple of issues in your code. Firstly, items is a normal variable and doesn't use the useState hook, and secondly, when injecting a variable's value into HTML, you need to use curly braces. Depending on what the API returns, you may need to return something like:

<div>
    {items.map((item) => {
       <div>{item.property}</div>
    })}
</div>

But anyway, here's the basic idea:

import React, {useState} from "react";
import { Row } from "react-bootstrap";
import * as Constants from '../Constants';
import './index.css';


function ActivitySuggestions(){
 
 const [items, setItems] = useState(null);
 React.useEffect(() => {
    const url = "https://www.boredapi.com/api/activity";
    fetch(url)
      .then((response) => response.json())
     .then((json) => (setItems(json)))
      .catch((error) => console.log(error));
  }, []);


  return(
    <div>{items}</div>
  );
}

export default ActivitySuggestions

CodePudding user response:

Use useState hook

import React, {useState} from "react";

function ActivitySuggestions(){
    const [items, setItems] = useState(null);

    React.useEffect(() => {
        const url = "https://www.boredapi.com/api/activity";
        fetch(url)
          .then((response) => response.json())
         .then((json) => setItems(json))
          .catch((error) => console.log(error));
      }, []);


    return(
        <div>
            {items ? JSON.stringify(items) : 'Loading...'}
        </div>
    );
}

export default ActivitySuggestions

there is issue in this code

return(
<div>items</div>

write like this:

return(
    <div>
        {items ? JSON.stringify(items) : 'Loading...'}
    </div>
)
  • Related