Struggling to craft an accurate GraphQL request to Yelp

As a newcomer to Apollo, I am facing some challenges while trying to send a basic GraphQL query to the Yelp server.

import React from 'react';
import { render } from 'react-dom';
import ApolloClient from 'apollo-boost';
import { setContext } from 'apollo-link-context';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import { ApolloProvider } from 'react-apollo';
import { yelpCredentials } from '../../../keys/yelp/config';
import 'cross-fetch/polyfill';
import App from './components/App';

const httpLink = createHttpLink({
  uri: 'https://api.yelp.com/v3/graphql',
});
const authLink = setContext((_, { headers }) => {
  const token = yelpCredentials.API_Key;
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
      'Content-Type': 'application/graphql',
    },
  };
});
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

client.query(
 ***[QUERY_CONTENT]***
 ,
}).then(console.log);

render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('app'),
);

I attempted the following queries:

client.query({
  query: gql`
  query business($id: String!) {
      business(id: $id) {
        name
        id
        alias
        rating
        url
      }
    }
  `,
  variables: { id: 'garaje-san-francisco' },
}).then(console.log);

The error encountered was: Uncaught (in promise) Error: Network error: Unexpected token < in JSON at position 0

query2:

client.query({
  query: gql`
      query business(id: "garaje-san-francisco") {
        name
        id
        alias
        rating
        url
      }
    }
  `,
}).then(console.log);

The error received was: "Syntax Error: Expected $, found Name "id""

query3:

 client.query({
  query: gql`
    query business($id: String!) {
      name
      id
      alias
      rating
      url
    }
  `,
  variables: {
    id: 'garaje-san-francisco',
  },
}).then(console.log);

Another error encountered: Uncaught (in promise) Error: Network error: Unexpected token < in JSON at position 0

I have successfully retrieved data using Postman https://i.stack.imgur.com/Wc3uE.jpg

Answer №1

const apolloClient = new ApolloClient({ uri: 'http://localhost:4000/graphql' });

I attempted to set up the configuration for the apollo-boost client using the ApolloClient constructor.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express does not respond to a blank request and the client is left wondering on separate ports without a reply

I am facing an issue with my small react client and express server setup. The react client runs on port 3000 while the express server runs on port 3001. Whenever I click a button, a request is sent to the server. However, the POST request seems to print an ...

The re-rendering of a functional component utilizing React.useCallback and React.memo() is occurring

I was delving into React concepts and eager to experiment with some new things. Here are a few questions that crossed my mind: Does every functional child component re-render when the parent state changes, even if it doesn't have any props? It seems ...

Having trouble with installing npm packages? The node-gyp has encountered an end of line error while scanning the common.gypi

As I try to fetch dependencies for my React app using npm i, I encounter the following error: gyp info spawn args 'build', npm ERR! gyp info spawn args '-Goutput_dir=.' npm ERR! gyp info spawn args ] npm ERR! Traceback (most recent ...

Strategies for Improving Usual React Components

When styling a mandatory TextField, you can refer to this example const styles = theme => ({ labelAsterisk: { color: "red" }, cssLabel: { color: "orange" }, cssRequired: { "&:before": { borderBottom: "2px solid orange" ...

Data on global map routes displayed in highcharts react

After reviewing the react highmaps documentation, it appears that they have saved the map data in a hardcoded manner. Take a look at Link 1 Check out Link 2 In various tutorials, I noticed that the data is retrieved from high maps itself by passing a ke ...

How to automatically fill a row in ReactJS/Material-Table when a specific "lookup" or dropdown option is chosen?

Query: How do I utilize the Material-Tables "lookup" function to automatically populate a row based on the selected option? I have an array containing crucial data values, and my goal is to prefill the row with information from the array when a selection ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

What is the process for setting the action column as the last column in a Material UI table in ReactJs?

https://i.stack.imgur.com/q2sTF.png I am trying to arrange the action column as the final column in my table setup. Below is the code snippet: <MaterialTable title="Patient List" columns={state.columns} data={data} onRowClick={(event, rowData) ...

Looking for a way to implement a functionality similar to setFieldError in Antdesign for Reactjs

I am currently attempting to manually change a field to an error or warning state after the form has been submitted. However, I am unable to locate a function similar to setFieldError on the form hook. In the image provided, my goal is to set the email f ...

Steps for aligning a grid column to the same height as the element above it and moving it to the left side

I have a setup using material UI where I have a grid positioned on top of a Paper element. Within the grid, there is a text input field in the first column that I want to match the height of the paper element and be aligned with its left border. I have tri ...

Ways to send properties using Links?

When attempting to pass the chart props through the Link react-router, I initially tried to do so via the route. However, this did not yield the expected result as each data has its own unique array number. Consequently, I determined that passing it throug ...

Why am I unable to access all elements within the map function?

Hey there, I have a function related query. Whenever I try to access my data, I can only reach the first index of each array. For instance, I have 5 different images of PlayStation, but on my webpage, I am only able to see one image. How can I resolve this ...

Managing the relationship between two asynchronous thunks

Two async thunks have been created using the createAsyncThunk() function from the redux-toolkit. For example: const getOrder = createAsyncThunk('a/getOrder', async (_, thunkAPI) => { // `userId` is obtained from API.getUser() // Attempted ...

Trigger the scroll into view of a specific component in NextJS when clicking a button that is located in a separate JS file

I recently started working with NextJS and I have my components spread across different JavaScript files. These components are then imported into a single file located in my "pages" folder (index.js). My goal is to be able to click on a button within the h ...

I can't seem to get React Fetch and the expressJS post method to cooperate - what could I be overlooking?

I have been diving into the world of React and recently ventured into working with expressJS. However, I encountered an issue with the POST method as the data is not being successfully posted to the server. While I believe my fetching of the post method is ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

Is there a way to change the color of a Material-UI snackbar without creating a new one for each color?

Is there a way to change the color of a snackbar in material-ui without creating a new one for each color? It seems that the example sandbox only has one color, while the others are static. ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...