0

I'm totally new to ReactJS and freshly completed my tutorial and now I'm working around with React. I started with just making a PHP file echo "Hello" and React.js fetching that response and displaying it on the website but it doesn't seem to work at all.

My PHP code:

<?PHP
  echo "Hello!";
?>

My React.js code:

const [data, newData] = useState(null);
useEffect(() => {
  fetch(//MY .php file link, NOT API just a php file echoing hello)
    .then((response) => response.json())
    .then(newData);
  });
        
  return (
    <>
      <div>
        { data }
      </div>
    </>
  );

1 Answer 1

1

In the first .then() of fetch, when you try to extract the JSON content from the response by using the json() method, you should use the .text() method instead as you're returning a simple string from your server, not a JSON object. Once you returned this text, you can update the state in the second .then().

Don't forget to include a dependency array in your useEffect, as without it you will always trigger another render after it runs. If you add an empty array as a dependency, it will only fetch on page load.

function App() {
  const [data, newData] = useState(null);

  useEffect(() => {
    fetch(URL)
      .then((response) => response.text())
      .then((response) => newData(response));
  }, []);

  return <div>{data ? data : 'No data yet...'}</div>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.