-1

I need to set value for my variable in API request and then use it in function outside request.

import React from 'react'

export default async (req, res) => {
  if (req.method === 'GET') {
    try {
      const imageToBase64 = require('image-to-base64')
      
      const [a,setA] = React.useState('')

      imageToBase64('url') // Path to the image
      .then(
          (response) => {
             setA(response)
          }
      )
      .catch(
          (error) => {
              console.log(error); // Logs an error if there was one
          }
      )
           console.log('a')
    } catch (error) {
      console.error(error)
    }
  }
}

The problem is that file I editing just use export default, it's not wrapped in class which extends React.Component and dont' use render function. How can I assigned response value to my variable?

justsimpleuser
  • 149
  • 1
  • 14
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Oct 15 '20 at 08:23

1 Answers1

0
import React, {useEffect, useState} from 'react'

export default const ApiCall = (req, res) => {
  const [a,setA] = useState('')
  useEffect(() => {
   if (req.method === 'GET') {
    try {
      const imageToBase64 = require('image-to-base64')
      imageToBase64('url') // Path to the image
      .then(
          (response) => {
             setA(response)
          }
      )
      .catch(
          (error) => {
              console.log(error); // Logs an error if there was one
          }
      )
           console.log('a')
    } catch (error) {
      console.error(error)
    }
  }
}, [req])
  
}
  • I tried this, but I'm keep getting error: `Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app` – justsimpleuser Oct 15 '20 at 08:29
  • You need to use functional component or class component. Please edit and past whole code in you post. –  Oct 15 '20 at 08:31
  • You need to read about useEffect. I will modify me answer now. –  Oct 15 '20 at 09:08