How to use the HTTP Request with React Native Expo?

I am trying to use this API in an app. The website mentions that it can be used with any language through the use of a HTTP request.

This is what I am doing in my code (Expo, Visual Studio Code)

const openAISummarizer = async() => {
   
    const apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
   
   
    fetch('https://api.openai.com/v1/completions/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apikey}`
      },
      body: JSON.stringify({
        model: "text-davinci-003",
        prompt: "Say this is a test",
        max_tokens: 7,
        temperature: 0,
      }),
    }).then(res => console.log(res.json().choices[0].text))
    .catch(error => {
      console.log(error);
    }); 
  }
      

  useEffect(()=>{
    openAISummarizer();
  }, [])

But I keep on getting this error:
Error: Objects are not valid as a React child (found: object with keys {_x, _y, _z, _A}). If you meant to render a collection of children, use an array instead.

Is there an issue with how I am entering the API key or something?

That’s a React error, not OpenAI error

1 Like

Right. I realized it was an issue with the async/await. I fixed it as so:

const openAISummarizer = async () => {
   
    const apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
   
    try {
      const response = await fetch('https://api.openai.com/v1/completions/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apikey}`
        },
        body: JSON.stringify({
          model: "text-davinci-003",
          prompt: "Say this is a test",
          max_tokens: 7,
          temperature: 0,
        }),
      })

      const json = await response.json();  
      console.log("this is the result", json)
    } catch (error) {
      console.error("this is the result", error);
    }
   
    
  }
      

  useEffect(()=>{
    openAISummarizer();
  }, [])
  

But now I am getting this error:

this is the result Object {
  "error": Object {
    "code": null,
    "message": "Invalid URL (POST /v1/completions/)",
    "param": null,
    "type": "invalid_request_error",
  },
}

EDIT: Solved it! I had to remove the “/” from the url. It should be this:

const response = await fetch('https://api.openai.com/v1/completions'

It’s https://api.openai.com/v1/completions. No trailing slash.

See docs

2 Likes

Yeah I just figured it out at the same time with my edit. Thanks though!