I am trying to create a dummy project with React JS and Im getting my data from SpaceX Graphql API. I have two components (Home, Details) and both components are supposed to grab data from the API. However, I query works in the Home component but it does not in the Details component. I used the exact same method and it doesn't seem to work. Do help me with this.
You can try the whole thing at https://github.com/affiqzaini/react-apollo-spacex if you want.
Here's my Home component which works:
import React from 'react';
import { Query } from 'react-apollo';
import gql from 'graphql-tag';
import { BrowserRouter, NavLink } from 'react-router-dom';
import Route from 'react-router-dom/Route';
import 'react-bulma-components/dist/react-bulma-components.min.css';
import './App.css';
import Details from './Details';
const POSTS_QUERY = gql`
{
rockets {
name
country
id
}
}
`;
function Home() {
return (
<BrowserRouter>
<Route
path='/'
exact
strict
render={() => {
return (
<div
className='tile is-ancestor'
style={{
justifyContent: 'space-evenly',
alignItems: 'center',
margin: 25
}}
>
<Query query={POSTS_QUERY}>
{({ loading, data }) => {
if (loading) return <p className='Loading'>Loading...</p>;
const { rockets } = data;
return rockets.map(post => (
<NavLink to={{ pathname: `/${post.id}` }}>
<div class='tile is-parent'>
<article
class='tile is-child box'
key={post.id}
style={{
backgroundColor: 'whitesmoke',
borderRadius: 10,
height: 400,
width: 300
}}
>
<figure
class='image container is-1by1'
style={{ marginBottom: 15 }}
>
<img
src={require(`./Images/${post.id.toString()}.jpg`)}
className='Rocket-Img'
alt='Rocket'
/>
</figure>
<h2>{post.name}</h2>
<h4>{post.country}</h4>
</article>
</div>
</NavLink>
));
}}
</Query>
</div>
);
}}
/>
<Route path='/:id' exact strict component={Details} />
</BrowserRouter>
);
}
export default Home;
Here's my Details component which does not work:
import React from 'react';
import { useParams } from 'react-router';
import { Query, ApolloProvider } from 'react-apollo';
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
import './App.css';
function Details() {
const rocketId = useParams();
const QUERY_ROCKET = gql`
{
rocket(id: "${rocketId}") {
id
active
boosters
company
cost_per_launch
name
stages
success_rate_pct
type
wikipedia
first_flight
country
description
}
}
`;
return (
<Query query={QUERY_ROCKET}>
{({ loading, data }) => {
if (loading) {
return <p className='Loading'>Loading...</p>;
} else {
const { detailsData } = data;
return detailsData.map(post => (
<div>
<p>{post.id}</p>
</div>
));
}
}}
</Query>
);
}
export default Details;
Here's the error I get: Error Image
Update: I found out that I get different type of data in the two queries. In Home (which works), I get an array of data. In my details component, I get an object. Is that why I cant use the map function?
detailsDatais undefined. Are you sure it's returned in yourdataobject?