React + GraphQL: dataArray.map is not a function - reactjs

I Just started learning graphQL and Apollo.
Below is the sample client side code using Apollo client.
I am providing data from nodemon express server.
console.log(data) shows the output from the server.
However i was trying to display the query result using the apollo client but i was unbale to do so. I am stuck in this , any help will be appreciated.
import React from "react"
import { Query } from "react-apollo";
import gql from "graphql-tag";
export const ExchangeRates = () => (
<Query
query={gql`
{
counterparty {
name
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
console.log(data) // Works fine as expected
var a= data.map(x=>{
return x.name
})
return <div> Data {a}</div> // stuck here ..how to display data
}}
</Query>
);
The following codes gives an error and says
TypeError: data.map is not a function
However the console.log(data) works fine and the following output:-

Your are doing wrong here... your array is inside data.counterparty...
try this
var a= data.counterparty.map(x=>{
return x.name
})

Related

URQL + React "typeError: Cannot read property '_react' of undefined"

I'm currently working through a urql+react tutorial found here while also adding graphQL API calls to my own application.
In the tutorial the following code is provided to send a query to the server and render components based on the result
const FEED_QUERY = gql`
{
feed {
links {
id
createdAt
url
description
}
}
}
`
const LinkList = () => {
const [result] = useQuery({ query: FEED_QUERY })
const { data, fetching, error } = result
if (fetching) return <div>Fetching</div>
if (error) return <div>Error</div>
const linksToRender = data.feed.links
return (
<div>
{linksToRender.map(link => <Link key={link.id} link={link} />)}
</div>
)
}
this code runs correctly when I implemented the tutorial myself but when I try to add this exact code to my own application I get the following error(s)
I have triple checked to make sure all the necessary urql and graphql dependencies are all installed in my application so I'm not sure what could be causing this issue.

TypeError: Cannot read property 'getPosts' of undefined - useQuery hook, react Functional Components

I did try searching for the same question but all of those were of either angular or unrelated,
I am trying to make a Social app using MongoDB, Express, React, Node, Graphql with Apollo, I am following a video from freecodecamp : Link to the video
In that video everything worked fine but in his deployed version he is having the same error as mine
react_devtools_backend.js:2450 TypeError:
Cannot read property 'getPosts' of undefined
at ae (Home.js:14)
at Jo (react-dom.production.min.js:3274)
link to the deployed app
My Code: I am dropping a link to my github repo containing the whole project : Link to github
repo
Stack Overflow was throwing too many indentation issues so i have linked my github above as there
is too much of code
I'm using semantic-ui for styling
I'm using graphql the fetch posts from MongoDB
Apollo Client for rendering data
This is the error I am getting in the Home.js:
Screen Shot of the error:
Make it simpler to debug, instead:
const {
loading,
data: { getPosts: posts }
} = useQuery(FETCH_POSTS_QUERY);
do:
const { data, loading, error } = useQuery(FETCH_POSTS_QUERY);
if(data) {
console.log(data);
const { getPosts: posts } = data;
}
if(error) {
console.log(error);
return "error"; // blocks rendering
}
this works but not when data is there and not always
"not when data", "not always"??? weird ... 'posts' can be defined only if data exists ... accessing it when undefined will fail, always ... you must check 'data'
You can/should render items (posts) ONLY when:
!loading
AND
data != undefined - if(data) or (data && in JSX
{loading && <h1>Loading posts..</h1>}
{data && (
<Transition.Group>
{posts &&
posts.map((post) => (
<Grid.Column key={post.id} style={{ marginBottom: 20 }}>
<PostCard post={post} />
</Grid.Column>
))}
</Transition.Group>
)}
use this code like this
const { loading, data: { posts } = {} } = useQuery(FETCH_POSTS_QUERY);
You need to define the query operation like:
export const FETCH_POSTS_QUERY = gql`
query GetPosts {
getPosts {
// fields
}
}
`
Alternatively, you can make use of alias to easily reference them.
export const FETCH_POSTS_QUERY = gql`
query GetPosts {
posts: getPosts {
// fields
}
}
`
const {
loading,
data: { posts } // uses alias directly. no need to rename
} = useQuery(FETCH_POSTS_QUERY);
const { loading, data: { getPosts: posts } = {} } = useQuery(FETCH_POSTS_QUERY)
This should solve the problem
THIS WILL WORK
write data.getPosts inside the grid
const { loading ,data , error } = useQuery(FETCH_POSTS_QUERY);
if (error) return Error! ${error.message};
{loading ? (<h1>Loading posts...</h1>)
: (data.getPosts &&
data.getPosts.map((post) => (
<Grid.Column key={post.id} style= {{ marginBottom: 20}}>
<PostCard post={post} />
</Grid.Column>

JS TypeError: Cannot Read Property "..." of Undefined, Despite DATA being returned?

I am following this Apollo Pagination tutorial:
Apollo Pagination Examples
Summary of my issue:
I have a known working GraphQL query that works in the playground. When I try to fetch data and use it in a React component, as outlined in that Apollo link above, I get the following error:
"TypeError: Cannot read property 'errorlogsConnection' of undefined"
However, when I check the response from the graphQL api in the web console, the query does in fact return data. Picture attached below.
I believe I'm probably trying to reference the object incorrectly but I can't spot what my mistake is.
Note: I have been able to query and use this same API endpoint in other React components for this very same project without issue.
Here is the code involved:
I am using this query, which works in my GraphiQL playground:
query errorlogsConnection($cursor: String) {
errorlogsConnection(orderBy: errorid_DESC, first: 4, after: $cursor) {
edges {
node {
errorid
errorlog
entrydate
}
}
pageInfo {
hasPreviousPage
hasNextPage
endCursor
startCursor
}
}
}
Here is the ReactJS code that I've adapted from their tutorial:
function ErrorLogsPagination() {
const {data: {errorlogsConnection: errorLogs}, loading, fetchMore, error} = useQuery(
ERROR_LOG_PAGINATION
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<ErrorLogs
entries={errorLogs || []}
onLoadMore={() =>
fetchMore({
variables: {
cursor: errorLogs.pageInfo.endCursor
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult.errorLogs.edges;
const pageInfo = fetchMoreResult.errorLogs.pageInfo;
return newEdges.length
? {
// Put the new comments at the end of the list and update `pageInfo`
// so we have the new `endCursor` and `hasNextPage` values
comments: {
__typename: previousResult.errorLogs.__typename,
edges: [...previousResult.errorLogs.edges, ...newEdges],
pageInfo
}
}
: previousResult;
}
})
}
/>
);
}
The data property will be undefined until the data is fetched from the server or the cache. To prevent the error, either avoid destructuring data until after loading is complete, or else provide default values where appropriate:
const {
data: {
errorlogsConnection: errorLogs
} = {},
loading,
fetchMore,
error,
} = useQuery(ERROR_LOG_PAGINATION)

React GraphQL - How to return the results of a Query component as an object to use in React context

I have a Query component which gets the information of the a user who has logged in. The query itself works but I am having trouble returning the results of the query as an object which I then want to pass to React.createContext()
I am using Apollo client to make my Query component in my React application.
The following is an example of my current code:
function getUser() {
return (
<Query query={query.USER_INFO}>
{({ loading, error, data }) => {
if (loading) return <div>Loading</div>;
if (error) return <div>error</div>;
const userInfo = {
name: data.user.name,
age: data.user.age,
}
}}
</Query>
);
}
//need userInfo object to go here
export const UserContext = React.createContext(userInfo);
How can I get the return of the Query to then use in React.createContext? The reason I want to do it this way is to avoid rewriting this Query in every component where I want info of the user who has logged in.
To be honest, to me it seems like you're just missing a return statement:
function getUser() {
return (
{({ loading, error, data }) => {
if (loading) return Loading;
if (error) return error;
const userInfo = {
name: data.user.name,
age: data.user.age,
}
return userInfo // ----- this here
}}
</Query>
);
}
//need userInfo object to go here
export const UserContext = React.createContext(userInfo);
but i didn't test it out and haven't taken this approach - give it a go see, if it helps

GraphQL Return Query Result as an Array

I have been following the React-Apollo and Node.js GraphQL Tutorials on https://www.howtographql.com/ and was able to get a demo up and running.
What I would like to do now is return the result of my query as an array.
My schema.graphql file looks like this:
type Query{
pullTickets (where: TicketWhereInput): [Ticket!]!
}
And the resolver looks like:
const resolvers = {
Query: {
pullTickets: (root, args, context, info,) => {
return context.db.query.tickets({}, info)
}
}
}
What I have tried so far is:
import React, { Component } from 'react';
import Query from "react-apollo/Query";
import gql from "graphql-tag";
const GET_TICKETS = gql`
query getTickets($startDate: DateTime!, $endDate: DateTime!) {
pullTickets (where: {
AND:[{DateCloseDate_gt: $startDate}, {DateCloseDate_lt: $endDate}]})
{
id
}
}
`;
export default function GetTickets ( startDate, endDate ) {
var temp = [];
<Query query={GET_TICKETS} variables={{ startDate, endDate }} >
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error!: ${error}`;
// This doesn't seem to do anything
temp = data.pullTickets
}}
</Query>
// temp is showing up as "undefined" in the console
console.log(temp);
return temp
}
I should be getting a list of Tickets but I am getting undefined.
How to use client.query or client.mutation without using jsx
I had the same issue, I wanted to use query without using any jsx, the solution is to use ApolloClient, at some point in your app you will use ApolloProvider which u will need to give it an instance of ApolloClient as a prop, all u have to do is export that client and u can then use it anywhere else not only in the ApolloProvider.
Here is an example
initApollo.js
this is where Apollo client is initialized.
import { ApolloClient } from 'apollo-client';
.
.
.
initApolloClient ({ uri }) => {
.
.
.
return new ApolloClient({
link,
cache,
});
}
export default initApolloClient
useClientWithoutJsx.js
import initApollo from './initApollo';
client = initApollo({ uri: 'http://localhost:4000' });
client.query(({query: SOME_QUERY, variables: {id: 2}) => {
// return data
})
does this answers your question ?

Resources