GraphQL query to pass mapQueriesToProps via connect() not firing - reactjs

So, I'm attempting to set the results of a graphQL query to mapQueriesToProps, and then pass the result onto the main interface/view of my app via connect(), but the query is not firing (as confirmed by devTools):
My code is as follows:
App.js
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// import { connect } from 'react-apollo';
import {
// gql,
graphql,
withApollo
} from 'react-apollo';
import gql from 'graphql-tag';
import * as actionCreators from '../actions/actionCreators';
// import client from '../apolloClient';
// import ApolloClient from 'apollo-client';
/*
Components
This is where the actual interface / view comes into play
Everything is in Main - so we import that one
*/
import Main from './Main';
const allPostsCommentsQuery = gql`
query allPostsCommentsQuery {
allPostses {
id
displaysrc
caption
likes
comments {
id
posts {
id
}
text
user
}
}
}
`;
const mapQueriesToProps = ({ ownProps, state }) => {
return {
posts: {
query: gql`
query allPostsCommentsQuery {
allPostses {
id
displaysrc
caption
likes
comments {
id
posts {
id
}
text
user
}
}
}
`,
// variables: {
// },
// forceFetch: false, // optional
// returnPartialData: false, // optional
},
};
};
export function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
var App = connect(
mapQueriesToProps,
mapDispatchToProps
)(Main);
export default App;
Main.js
import React from 'react';
import { Link } from 'react-router';
const Main = React.createClass({
render() {
return (
<div>
<h1>
<Link to="/">Flamingo City</Link>
</h1>
{/* We use cloneElement here so we can auto pass down props */}
{ React.cloneElement(this.props.children, this.props) }
</div>
);
}
});
export default Main;
My app.js into which App.js is imported into:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router'
import 'babel-polyfill';
import { ApolloProvider, graphql, gql } from 'react-apollo';
import client from './apolloClient';
/*
Import Components
*/
import App from './components/App';
import Single from './components/Single';
import PhotoGrid from './components/PhotoGrid';
/* Import CSS */
import css from './styles/style.styl';
/* Import our data store */
import store, { history } from './store';
/*
Error Logging
*/
import Raven from 'raven-js';
import { sentry_url } from './data/config';
if(window) {
Raven.config(sentry_url).install();
}
/*
Rendering
This is where we hook up the Store with our actual component and the router
*/
render(
<ApolloProvider store={store} client={client}>
{ /* Tell the Router to use our enhanced history */ }
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={PhotoGrid} />
<Route path="/view/:postId" component={Single}></Route>
</Route>
</Router>
</ApolloProvider>,
document.getElementById('root')
);
What am I overlooking?

I resolved the issue by doing the following:
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
gql,
graphql
} from 'react-apollo';
import * as actionCreators from '../actions/actionCreators';
/*
Components
This is where the actual interface / view comes into play
Everything is in Main - so we import that one
*/
import Main from './Main';
const allPostsCommentsQuery = graphql(gql`
query allPostsCommentsQuery {
allPostses {
id
displaysrc
caption
likes
comments {
id
posts {
id
}
text
user
}
}
}
`);
/*
This will bind our actions to dispatch (make the fire-able)
and make the actions available via props
*/
export function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
const App = connect(
mapDispatchToProps
);
export default App(allPostsCommentsQuery(Main));

Related

When I connect more clients on Apollo React only the last client receive GraphQL Subscriptions updates

Basically, when there is more than one client connected, only the last client connected receives GraphQL subscriptions data through the web socket.
This doesn't happen with old React classes, it happens only when I use stateless functions through Apollo Hooks Provider. I tried several methods already, such as subscribeToMore (that was working perfectly with classes) or useSubscription and in general everything that is suggested on this page https://www.apollographql.com/docs/react/data/subscriptions/.
These are the relevant parts of the component code, the subscribeToMore part is basically copy-pasted from an old React class where it works perfectly on the same project.
(If there are missing functions or variables, it's just because I avoided to post a lot of clutter, the code has been tested and runs with no error except for the subscriptions problem)
import React, { useEffect, useState } from 'react';
import { compose } from 'redux';
// other imports
function CommentsPanel(props) {
const { loading, documentComments: comments } = commentsQuery;
const [subscribed, setSubscribed] = useState(false);
useEffect(() => {
if (loading || comments == null || subscribed) return;
console.log(commentsQuery);
commentsQuery.subscribeToMore({
document: ON_COMMENT_ADDED,
variables: {
documentId: projectId,
userId: Meteor.userId(),
},
updateQuery: (previousResult, { subscriptionData }) => {
console.log('On comment added subscription');
return {
...previousResult,
documentComments: [
subscriptionData.data.commentAdded,
...previousResult.documentComments,
],
};
},
});
// other similar subscriptions
setSubscribed(true);
}, [loading, comments, subscribed, commentsQuery, projectId]);
//render and a bunch of other stuff
export default compose(
graphql(DOCUMENT_COMMENTS, {
name: 'commentsQuery',
options: ({ projectId }) => ({
variables: {
documentId: projectId,
},
}),
}),
withStyles(styles),
)(CommentsPanel);
And this is the client
import React from 'react';
import 'babel-polyfill';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { hydrate } from 'react-dom';
import { BrowserRouter, Switch } from 'react-router-dom';
import { ThemeProvider as MuiThemeProvider } from '#material-ui/core/styles';
import { ApolloProvider } from 'react-apollo';
import { ApolloProvider as ApolloHooksProvider } from '#apollo/react-hooks';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import { Bert } from 'meteor/themeteorchef:bert';
import CssBaseline from '#material-ui/core/CssBaseline/CssBaseline';
import reducerApp from '../../reducers';
import apolloClient from './apollo';
import App from '../../ui/layouts/App';
import theme from '../theme';
Bert.defaults.style = 'growl-bottom-right';
Accounts.onLogout(() => apolloClient.resetStore());
const store = createStore(reducerApp);
const rootElement = document.getElementById('react-root');
Meteor.startup(() =>
hydrate(
<MuiThemeProvider theme={theme}>
<CssBaseline />
<ApolloProvider client={apolloClient}>
<ApolloHooksProvider client={apolloClient}>
<Provider store={store}>
<BrowserRouter>
<Switch>
<App />
</Switch>
</BrowserRouter>
</Provider>
</ApolloHooksProvider>
</ApolloProvider>
</MuiThemeProvider>,
rootElement,
),
);

React With Redux Thunk and Apollo Graphql - How to access client.query?

This is my app.js
import React from 'react'
import { Provider } from 'react-redux'
import { View } from 'react-native'
import { createStore, applyMiddleware } from 'redux'
import ReduxThunk from 'redux-thunk'
import Reducers from './redux'
import Routes from './config/routes'
import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost'
import { ApolloProvider } from 'react-apollo'
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: new HttpLink({
uri: '...',
}),
})
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
initialized: true
}
}
render() {
return (
<View style={{ flex: 1 }}>
<ApolloProvider client={client}>
<Provider store={store}>
<Routes />
</Provider>
</ApolloProvider>
</View>
)
}
}
const store = createStore(Reducers, {}, applyMiddleware(ReduxThunk))
export default App
Ok, so far...basic.
This will render the initial file of my route: welcome.js
import React from 'react'
import {...} from 'react-native'
import { Actions } from 'react-native-router-flux'
import style from './style'
import { connect } from "react-redux"
import gql from 'graphql-tag'
class Welcome extends React.Component {
constructor(props) {
const LOGIN_MUTATION = gql`
mutation {
login(
email:"test#test.com"
password:"1234"
) {token}
}
`
// Bellow will not work..I've no idea how to call the client that
// I set at <ApolloProvider client={client}>
client
.mutate({
mutation: LOGIN_MUTATION
})
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
const mapStateToProps = state => (
{
}
)
export default connect(mapStateToProps,
{
})(Welcome)
So, the client was defined on my app.js that's apply the provider and inject the routes.
I'd like to know how to be capable to execute the client defined at app,js into welcome.js
It's highly recommended that you switch for the new React Hooks version, using them, you can simply write const client = useApolloClient() to get access to your client instance:
import { useApolloClient } from '#apollo/react-hooks';
const Welcome = () => {
const client = useApolloClient();
return <h1>Welcome</h1>;
}
And regarding the ApolloProvider, it is configured in the same manner was you did, except that you can import it directly from the hooks package too, i.e import { ApolloProvider } from '#apollo/react-hooks -- and you can remove the react-apollo therefore.
See more details about hooks here: https://www.apollographql.com/docs/react/hooks-migration/.
But in case you really want to stay using class components, you can do:
import { getApolloContext } from 'react-apollo';
class Welcome extends React.Component {
...
}
Welcome.contextType = getApolloContext();
And then you'll be able to access the client using this.context.client inside your class:
class Welcome extends React.Component {
render() {
console.log('client', this.context.client);
return ...;
}
}
Welcome.contextType = getApolloContext();
You can use ApolloConsumer in your component to get access to the client:
To access the client directly, create an ApolloConsumer component and provide a render prop function as its child. The render prop function will be called with your ApolloClient instance as its only argument.
e.g.
import React from 'react';
import { ApolloConsumer } from "react-apollo";
const WithApolloClient = () => (
<ApolloConsumer>
{client => "We have access to the client!" /* do stuff here */}
</ApolloConsumer>
);

Connected component not receiving store props n Redux

I was doing a bit of refactoring and tried connecting a higher level component to redux using connect() but the component I'm connecting keeps giving me empty props.
I've included the relevant code, I've structured my redux reducers into a ducks format, so the actions/creators and reducers are in one module file.
The files are containers/login.js, presentation/login.js, presentation/logins.js, app.js and the root index.js.
When I decided to rename some actions, files and reducers, moved the connect to a higher component, the connection stopped working and now I have empty props.
Help much appreciated.
// containers/login.js
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'
import { fetchPage } from '../redux/modules/Login';
import Login from '../presentation/Login';
const mapStateToProps = (state) => {
return {
page: state.page,
forms: state.forms
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchPage: () => dispatch(fetchPage())
} // here we're mapping actions to props
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Login);
// redux/modules/login.js
import fetch from 'cross-fetch';
const RECIEVE_FORM = 'RECIEVE_FORM';
export const receiveForm = (response) => ({
type: RECIEVE_FORM,
forms: response.forms
})
const initialState = {
page: "",
forms: []
}
// MIDDLEWARE NETWORK REQUEST DISPATCHER
export const fetchPage = () => {
return dispatch => {
return fetch('http://localhost:3001/login')
.then(
response => response.json(),
)
.then(
response => dispatch(receiveForm(response))
)
}
}
// REDUCER COMPOSITION CALL EXISTING REDUCERS
// REDUCER COMPOSITION PATTERN
// ACCUMULATIVE ACTION REDUCER
export default function Login(state = initialState, action){
switch (action.type){
case RECIEVE_FORM:
return {
...state,
forms: action.forms
}
default:
return state;
}
}
// presentation/login.js
import React, { Component } from 'react';
import styled from 'styled-components';
import Wrapper from '../components/Wrapper';
import Card from '../components/Card';
import Text from '../components/Text';
import Logo from '../components/Logo';
import FormGroup from '../components/FormGroup';
const WrapperLogin = styled(Wrapper)`
.login__card{
padding: 4.5rem 2.5rem 2rem 2.5rem;
}
`;
const BoxLogo = styled.div`
.login__logo{
display: block;
margin: 0 auto;
}
`;
export default class Login extends Component{
componentDidMount() {
console.log(this.props)
//this.props.fetchPage();
}
render(){
return(
<main>
<WrapperLogin className="login">
<Card className="login__card">
<BoxLogo>
<Logo className="login__logo" width={187.36} height={76.77} />
</BoxLogo>
<FormGroup name="login" className="login_formGroup" />
</Card>
<Text primitive="p" margin='4px 0 0 0' size="0.8rem" textAlign="center" display='block'>Brought to you by WORLDCHEFS</Text>
</WrapperLogin>
</main>
)
}
}
// app.js
// manage routes here
//import _ from 'lodash';
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import Login from './presentation/Login';
type Props = {
}
type State = {
mode: string
};
export default class App extends Component <Props, State> {
constructor(){
super();
this.state = {
...this.state,
mode: 'mobile'
}
}
render(){
return(
<ThemeProvider theme={{ mode: this.state.mode }}>
<Login />
</ThemeProvider>
)
}
}
// root
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './redux/configureStore';
import registerServiceWorker from './registerServiceWorker';
import App from './App';
import { injectGlobal } from 'styled-components';
import styles from './assets/styles';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root')
);
The reason your props in Login component are empty is because you are not actually using the connected Login container, As you have mentions its in containers/login
So in your App.js change the import of login from ./presentation/login to
import Login from '/path/to/containers/Login';
You have imported presentation component in your app.js rather than container component. Please import your container component like below
import Login from './containers/login.js';
This will solve the problem as per my understanding from your code

How to get Routing History to Components not in Route?

I have some components that are not in my route(they are components to load up some part of my site but have nothing to do with navigation).
I however want to have the route history available to these components as some of the do ajax requests and if the user has lost authentication I want to kick them back to my home page.
I have no clue though how to pass the history to components so I could something like
this.props.history.replace(null, "/")
I am using: https://github.com/reactjs/react-router
Edit
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as ReactRouter from "react-router";
class App extends React.Component {
componentWillReceiveProps(nextProps) {
if (localStorage.accessToken === undefined) {
//nextProps.history.replace(null, "/");
}
}
render() {
return (
<div>
<NavigationContainer route={this.props.route} /> // want to pass history into this component so I can use it
</div>
);
}
}
function mapStateToProps(state) {
return {
//states
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
//binding
}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(App);
Edit 2
Here is my NaviagationContainer
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import { IndexLink, withRouter } from 'react-router';
class SideNavContainer extends React.Component {
componentWillMount() {
let props = this.props;
this.props.fetchStorage().then(function (response) {
//stuff
}).catch(function (response) {
// here is where I want to use it
if(response.response.status == 401) {
props.router.replace(null, "/");
}
});
}
render() {
return (
// return
)
}
}
function mapStateToProps(state) {
return {
//reducers
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
//bind
}, dispatch);
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps)(SideNavContainer));
my router
ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Home}></IndexRoute>
<Route path="app" name="app" component={App}></Route>
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
Seems like when using withRouter. Replace() does not work for me at all. Not in my NaivgationContainer nor in my App Component.
Yes, you can use push()/replace()
https://github.com/reactjs/react-router/blob/master/docs/API.md#pushpathorloc
This might give you a better answer: https://stackoverflow.com/a/31079244/5924322
//this HoC gives you the `router` which gives you push()
import { withRouter } from 'react-router'
Edit:
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import { withRouter } from "react-router";
class App extends React.Component {
componentWillUpdate(nextProps) {
if (localStorage.accessToken === undefined) {
nextProps.router.replace(null, "/");
}
}
render() {
return (
<div>
<NavigationContainer route={this.props.route} /> // want to pass history into this component so I can use it
</div>
);
}
}
function mapStateToProps(state) {
return {
//states
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
//binding
}, dispatch);
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps)(App));

Way to use react-router and redux on react-native

I'm started to use react-native (i'm from react-js), and i'm trying to implement my first little app with a router and redux as I do in web development with reactjs.
But i met a problem, and i can't to fix it.
so i'm on this way :
Index.ios.js
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux'
import { NavBar, Route, Router, Schema, TabBar, TabRoute } from 'react-native-router-redux';
import configureStore from './src/store/configureStore'
const store = configureStore()
import Index from './src/components/index'
class ole extends Component {
render() {
return (
<Provider store={store}>
<Router initial="index">
<Route name="index" component={Index} />
</Router>
</Provider>
)
}
}
AppRegistry.registerComponent('ole', () => ole);
store/configureStore.js
import { createStore, applyMiddleware } from 'redux'
import promise from 'redux-promise'
import reducer from '../reducers'
export default function configureStore(initialState){
const store = createStore(
reducer,
applyMiddleware(promise)
)
return store
}
reducers/index.js
import { combineReducers } from 'redux'
const INITIAL_STATE = {
test: [],
errors: undefined
}
initTestReducer = (state = INITIAL_STATE, action) => {
return state
}
export default combineReducers({
test: initTestReducer
})
if do exactly like that i get this error in my simulator on iOS :
Super expression must either be null or a function, not undefined
but if my index.ios.js look like that, it works perfectly :
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux'
import { NavBar, Route, Router, Schema, TabBar, TabRoute } from 'react-native-router-redux';
import configureStore from './src/store/configureStore'
const store = configureStore()
import Index from './src/components/index'
class ole extends Component {
render() {
return (
<Provider store={store}>
<Index />
</Provider>
)
}
}
AppRegistry.registerComponent('ole', () => ole);
So error come from Router
get u an idea ?
Thank's a lot :)

Resources