0
votes

I'm creating a simple React app with graphql, I'm using strapi as the server.

In Strapi I have a Vechicle collection type with a name field and a make field.

In the name field I have car and in make I have volvo, saab, audi, ford

I'd simple like to display car and the makes in a select menu.

The query to get the data

import gql from 'graphql-tag';

export const GET_ALL_CARS = gql `
    query Cars{
        cars{
            _id
            name
            makes
        }
    }
`

The react page

import React from 'react';
import { GET_ALL_CARS } from './queries';
import {Vechicles} from './generated/Vechicles'
import { useQuery } from "@apollo/react-hooks";

const App:React.FC = () => {

  const {data, loading} = useQuery<Vechicles>(GET_ALL_CARS, {})

  if(loading) return <div>Loading</div>

  if(!data) return <div>No Data</div>

  return (
    <div className="App"> 
      <h1>Vehicles</h1>
      {
        data && data.vechicles && data.vechicles.map(vechicle => (
          <div>
            //car displays ok
            {vechicle?.name}
            //trying to create an array here from the string of makes
            const makes_arr = {car?.makes ?? ''}.split(',')
            <select>
              {
                makes_arr.map(make = > {
                    return(
                        <option>{make}</option>
                    )
                })
              }
            </select>
          </div>
        ))
      }
    </div>
  );
}

export default App;

How do I simple display the comma seperated list in a select menu.

1
Do you have makes as an Array?somethings like ['volvo', 'saab', 'audi', 'ford'] - Alex
cars or vechicles - choose one, matching your [real] query - xadm

1 Answers

1
votes

You can't create an array in this place because it's a part of the JSX. Try to create array inline in your select.

I have removed optional chaining because it's not supported by the editor.

function App() {
  const data = {
    vehicles: [
      {
        name: "car",
        makes: "volvo, saab, audi, ford"
      },
      {
        name: "car2",
        makes: "volvo, saab, audi, ford"
      }
    ]
  };

  return (
    <div className="App">
      <h1>Vehicles</h1>
      {data &&
        data.vehicles &&
        data.vehicles.map(vehicle => (
          <div>
            {vehicle.name}
            <select>
              {vehicle.makes
                .split(",")
                .map(make => <option>{make.trim()}</option>)}
            </select>
          </div>
        ))}
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root" />