Home > Blockchain >  Why does my React Native app make this request over and over again?
Why does my React Native app make this request over and over again?

Time:10-25

I've so far tested only on Android. I want to get a JSON from my server and display the information as cards on the app. And it kind of works; it displays the correct data, but launches the request to my server hundreds of times, over and over again.

This is my code for the activity I'm having problems with.

function WorkOrders({ navigation }) {
  const [data, setData] = useState("")
  fetch(`https://www.example.com/workorder?user=${global.email}`, {
              method: 'POST',
              headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
              }
  })
  .then((response) => response.json())
  .then((response) => {
    setData(response)
  })
  if(!!data["id"]){
    return (
      <ScrollView>
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Work Orders assigned to me</Text>
        <Card>
        <Card.Title>Work Order #{data["id"]}</Card.Title>
            <Card.Divider/>
            <Text>Creation date: {data["creationDate"]}</Text>
            <Text>Due Date: {data["dueDate"]}</Text>
            <Card.Divider/>
            <Text>Work Location: {data["workLocation"]}</Text>
            <Card.Divider/>
            <Text>Description: {data["workDetails"]}</Text>
        </Card>
      </View>
      </ScrollView>
    );
  } else {
    return(
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>You don't have any assigned work orders.</Text>
    </View>
    );
  }
}

I'm very new to React Native, but I think my problem could be in where exactly am I running the fetch request, or how I'm reading the data.

Additionally, this view is linked to other views, using a navigation stack. I don't think that's the problem, as my log in screen behaves normally, launching a single request and directing me to the work orders screen on a correct log in.

CodePudding user response:

You've caused a render loop.

If you set state in the component body like this, it will cause it to re-render. Re-rendering will cause the data fetching code to re-run which sets state again. Instead you should de-couple the data fetching and UI. You could do this by fetching data "higher up" in your app/component tree and passing it down as props.

Alternatively, you could wrap your data fetching code in useEffect so that it is only called once.

  useEffect(()=>{
    fetch(`https://example.com/`, {
                method: 'POST',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json'
                }
    })
    .then((response) => response.json())
    .then((response) => {
      setData(response)
    })
  },[])

  • Related