0

I am using Php with react js ,there is constant declared in react js constant file that is used all over the application ,initially it was hardcoded in react js like Export const thumburl="www.example.com"; and its imported in almost every part of application now the requirement is to generate this URL dynamically from db.so i created a php file which will return this url i want to use it in react js constant file and export that ,tried several things but wasn't able to get results. it would be great help if any one can provide me the full working method to do this Note : react js is not my domain

async function githubUsers() {
    let response = await fetch('https://example.com/api.php')
    let users = await response.json()
    return users;
}

export const thumbUrl=githubUsers();

tried above code but it couldn't assign the value below is the sample php code

     <?php
if (isset($_SERVER['HTTP_ORIGIN'])) { 
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); 
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    }
    $data = 'www.example.com/gallery/thumbs/';
    header('Content-Type: application/json');
    echo json_encode($data);

1 Answers1

0

The issue here is that you are fetching the constant using an async method so thumbUrl essentially contains a promise. If you were in NodeJS you would simply add an await statement: const thumbUrl = await githubUsers(); but in React you will want to fetch this using useEffect and store it in the state with useState such as:

export function SomeConponent() {
  const [thumbUrl, setThumbUrl] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://example.com/api.php');
      const data = await response.json();
      setData(data);
    };

    fetchData();
  }, []);

  return (
    <div>ThumbsURL: { thumbsUrl }</div>
  )
}

Here's a nice write up. To store data throughout app you would want to use something like useContext - here's a post on this.

That being said many frameworks such as Next.js have "prefetching" methods made to do initial fetches like this.

cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • throwing Module build failed: SyntaxError: C:/xampp/htdocs/p2-server/extra-gallery-V-2/src/app/constants/Constants.js: 'return' outside of function (32:2) also can you tell me how can i export it then i mean thumbsurl – Farhan Sheikh Jul 23 '23 at 20:14
  • Well probably not just paste the return statements... The useEffect is meant to be inside your React component. if you intend to have this available throughout your app I would explore useContext/useReducer though that will be a bit of reading.... But again this might depends on your framework. I've updated the answer a bit though this is meant to show a single page/component usage – cyberwombat Jul 24 '23 at 02:51