How to pass a const variable from one component to another react - reactjs

Hello I am trying to add Apollo to my react app and in the documentation it says to wrap you app in the <ApolloProvider client={client}> tag and pass client in as a variable like so:
import React from 'react';
import ReactDOM from 'react-dom';
import PageLayout from './components/page-layout'
import CreateApolloClient from './apollo-settings'
import { ApolloProvider } from '#apollo/react-hooks';
import ApolloClient from 'apollo-boost';
import {BrowserRouter} from 'react-router-dom';
const client = new ApolloClient({
uri: 'http://localhost/headless-cms/admin/',
fetchOptions: {
mode: 'no-cors',
},
});
ReactDOM.render(<ApolloProvider client={client}><BrowserRouter><PageLayout /></BrowserRouter></ApolloProvider>, document.getElementById('site-wrapper'));
However I want to remove the const client from the index.js page and move it into another template just to keep things organised like so:
import React from 'react';
import { ApolloProvider } from '#apollo/react-hooks';
import ApolloClient from 'apollo-boost';
const CreateApolloClient = () => {
const client = new ApolloClient({
uri: 'http://localhost/headless-cms/admin/',
fetchOptions: {
mode: 'no-cors',
},
});
}
export default CreateApolloClient;
What I am struggling with is when importing CreateApolloClient into the index.js page how do I then access the const client and pass it into the <ApolloProvider client={client}>
Thank you for any help in advanced

You should return the apollo client instance in your function and export the createApolloClient.
import { ApolloProvider } from '#apollo/react-hooks';
import ApolloClient from 'apollo-boost';
export const createApolloClient = () => {
return new ApolloClient({
uri: 'http://localhost/headless-cms/admin/',
fetchOptions: {
mode: 'no-cors',
},
});
}
export default CreateApolloClient;
import React from 'react';
import ReactDOM from 'react-dom';
import PageLayout from './components/page-layout'
import {createApolloClient} from './apollo-settings'
import {BrowserRouter} from 'react-router-dom';
import { ApolloProvider } from '#apollo/react-hooks';
const client = createApolloClient();
ReactDOM.render(<ApolloProvider client={client}><BrowserRouter><PageLayout /></BrowserRouter></ApolloProvider>, document.getElementById('site-wrapper'));

Related

Cannot read properties of undefined (reading 'bind') useQuery

I have this code right here
import React from "react";
import { useQuery } from "#apollo/react-hooks";
import gql from "graphql-tag";
const FETCH_POSTS_QUERY = gql`
{
getMovies {
id
title
}
}
`;
function Home() {
const { loading, data } = useQuery(FETCH_POSTS_QUERY);
if (data) {
console.log(data);
}
return (
<div>
<h1>Home</h1>
</div>
);
}
export default Home;
and when I'm running it I get lots of errors in my console. I'm not sure what I’m doing wrong.
I can tell it's caused by how useQuery is used i think. I'm not sure what's wrong though.
thanks!
I faced the same problem today, the way of useQuery that you used is correct.
This is my original code in ApolloProvider component:
import React from 'react';
import App from './App';
import { ApolloProvider } from '#apollo/react-hooks';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import ApolloClient from 'apollo-client';
const httpLink = new createHttpLink({
uri: "http://localhost:5000"
})
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})
export default(
<ApolloProvider client={ client }>
<App />
</ApolloProvider>
)
I found using apollo-client dependency would cause the errors. Then I changed it and installed #apollo/client at 3.5.10 version instead to import ApolloClient. And It finally works fine.
import React from 'react';
import App from './App';
import { ApolloProvider } from '#apollo/react-hooks';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
// import ApolloClient from 'apollo-client';
import { ApolloClient } from '#apollo/client';
In addition, I've also tried to use #apollo/client at the newest version. It worked successfully as well.
I believe the issue is in the GraphQL schema, you are missing query in it. Try using the following schema:
const FETCH_POSTS_QUERY = gql`
query {
getMovies {
id
title
}
}
`;
I faced the same problem because of an old tutorial.
I configured my Apollo client in the wrong way.
Do the same as described in the get started guide from graphql and it will work perfect.

running React Native app with Redux toolkit throws an error

When i try to the run app it shows a red screen with this error in the terminal
Error: Unable to resolve module `../../../../src/assets/images` from `node_modules/#reduxjs/toolkit/dist/redux-toolkit.cjs.production.min.js`:
but It occuurs on iOS as well
The only way to make it go so far has been uninstalling react-redux. I do not have any imports in my code that point to src/assets/images as I dont have an assets/images directory to begin with.
My index.js:
import React from 'react';
import 'expo-asset';
import 'react-native-gesture-handler';
import {AppRegistry, View} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import { Provider as ReduxProvider } from 'react-redux';
import store from 'src/redux';
import React from 'react';
import 'expo-asset';
import 'react-native-gesture-handler';
import {AppRegistry, View} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import { Provider as ReduxProvider } from 'react-redux';
import store from 'src/redux';
const reduxApp = () => (
<ReduxProvider store={store}>
<App />
</ReduxProvider>
)
AppRegistry.registerComponent('main', () => reduxApp);
Redux store:
import { configureStore, getDefaultMiddleware} from '#reduxjs/toolkit';
import logger from 'redux-logger';
import { persistStore } from 'redux-persist';
import reducer from './reducers'
const middleware = [...getDefaultMiddleware(), logger]
const store = configureStore({
reducer,
middleware,
})
export const persistor = persistStore(store);
export default store;
metro.config.js:
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
babel.config.js
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
alias: {
src: './src',
screens: './src/screens',
redux: './src/assets/images',
assets: './assets',
},
},
],
],
};
};
The problem is your babel.config.js file. I'm guessing that you copy and pasted some code from somewhere else without understanding what it means.
redux: './src/assets/images',
This line right here tells the compiler that the location of the redux module is ./src/assets/images. It will look for the redux source code in that folder, which doesn't exist, instead of the default location which is ./node_modules/redux.
You don't want this so delete that line.

How can I get my http and subscription to work on client with graphQL?

I finally finished my backend with apollo.
Now I moved to the frontend.
I made it work with the normal http connection and fetched some messages from the server (chat app).
Now I also tried to connect the subscription link to it (which was very confusing in itself because there are a few examples outside and everybody does it a bit differently, but neither worked).
So here is how my index file looks on react frontend:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ApolloClient } from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { WebSocketLink } from "apollo-link-ws";
import { ApolloLink } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/graphql`,
options: {
reconnect: true
}
});
// Create an http link:
const httpLink = new HttpLink({
uri: "http://localhost:4000/graphql"
});
const link = ApolloLink.from([httpLink, wsLink]);
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
I also tried different methods for example with split from apollo-link like this:
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
I also tried it with ApolloClient from apollo-boost instead of apollo-client.
Can somebody please help me out, because I can't get it to work.
Error message is always:
WebSocket connection to 'ws://localhost:4000/graphql' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
If you want to see the full code: https://github.com/SelfDevTV/graphql-simple-chat

Helmet errors with renderStatic

I'm trying to setup Helmet npm using SSR within my meteor application and I'm getting the error, Error running template: TypeError: Cannot read property 'renderStatic' of undefined at sink. I'm new to using SSR so I'm not following what I'm missing here. Very nooooob question.
Path: server/main.js
import React from "react";
import PropTypes from 'prop-types';
import { onPageLoad } from "meteor/server-render";
import { renderToNodeStream } from "react-dom/server";
import { ServerStyleSheet } from "styled-components"
import { Helmet } from 'react-helmet';
import App from "/imports/server/app/App";
onPageLoad(sink => {
const sheet = new ServerStyleSheet();
const appJSX = sheet.collectStyles(
<App location={sink.request.url} />
);
App.propTypes = {
location: PropTypes.object,
};
const htmlStream = sheet.interleaveWithNodeStream(
renderToNodeStream(appJSX)
);
sink.renderIntoElementById("react-root-app", htmlStream);
const helmet = Helmet.renderStatic();
sink.appendToHead(helmet.meta.toString());
sink.appendToHead(helmet.title.toString());
});
Since Helmet is default export you need to import it like
import Helmet from 'react-helmet';
But not
import { Helmet } from 'react-helmet';
However, the latest version does not have a default import.
You must import it like this.
import { Helmet } from 'react-helmet';
This is as per the version
"react-helmet": "^6.0.0",

Cant connect React to Graphcool backend

Im trying to get a basic React + Graphcool project setup.
Ive initialised the Graphcool backend so I can see the playground at: https://api.graph.cool/simple/v1/MY-KEY
I can run this query in the playground and see results:
query {
allGroups {
id
description
}
}
However I cant connect this to the React front-end. This is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
// GraphQL
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
// Components
import App from './components/App/App';
const httpLink = new HttpLink({
uri: 'https://api.graph.cool/simple/v1/MY-KEY',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('App'),
);
In App.js:
import React from 'react';
import gql from 'graphql-tag';
import graphql from 'react-apollo';
const myQuery = gql`
query {
allGroups {
id
description
}
}
`;
const App = () => {
return (
<div>
<h1>Application</h1>
<h2>Groups:</h2>
</div>
);
};
// export default App;
export default graphql(myQuery)(App);
But I get an error:
Uncaught TypeError: (0 , _reactApollo2.default) is not a function
I don't know if this relevant or not but my IDE gives me the following error on the 'allGroups' line in App.js:
cannot query field "allGroups" on type "Query"
thats graphql import error, lets try this
In App.js:
import { graphql, } from 'react-apollo';
you'd better using a graphcool play ground to test you query and mutation
. then connect to React.Otherwise, there are many detail to debug.
here is my procedure
graphcool deploy is ok?
go to playground schema is ok?
query and mutation is ok?
configure apollo client and connect to React component. is ok?
In the component console.log(this.props.data) is ok ?
This is my flow.
And the most thing when you add some schema and resolvser, you must be add then to graphcool.yaml files. otherwise, graphcool can't find you schema and query method.
Is this your address?
here is mine
can you see difference?

Resources