Created
December 21, 2018 21:16
-
-
Save jmn/c3f7c4489cd5f759808a62b48352ce87 to your computer and use it in GitHub Desktop.
React redirect in render function warning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Query } from "react-apollo"; | |
import gql from "graphql-tag"; | |
const Q = gql` | |
query allPosts($cursor: String) { | |
allPosts(username: "jmn", first: 1, after: $cursor) { | |
edges { | |
node { | |
id | |
title | |
content | |
} | |
} | |
pageInfo { | |
startCursor | |
endCursor | |
} | |
} | |
} | |
`; | |
export const updQuery = (previousResult, { fetchMoreResult }) => { | |
// const newEdges = fetchMoreResult.allPosts.edges; | |
const pageInfo = fetchMoreResult.allPosts.pageInfo; | |
return { | |
allPosts: { | |
__typename: previousResult.allPosts.__typename, | |
edges: fetchMoreResult.allPosts.edges, | |
pageInfo | |
} | |
}; | |
}; | |
class Posts extends React.Component { | |
constructor(props) { | |
super(props); | |
this.myRef = React.createRef(); | |
console.log("props", this.props); | |
} | |
handleNext = (fetchMore, data) => { | |
fetchMore({ | |
variables: { cursor: data.allPosts.pageInfo.endCursor }, | |
updateQuery: updQuery | |
}); | |
window.scrollTo(0, 0); | |
//window.scrollTo(0, this.myRef.current.offsetTop); | |
//this.props.history.push("#!/" + data.allPosts.pageInfo.endCursor); | |
this.props.history.push("/post/" + data.allPosts.pageInfo.endCursor); | |
}; | |
render() { | |
return ( | |
<Query query={Q} variables={{ cursor: this.props.match.params.id }}> | |
{({ loading, error, data, fetchMore }) => { | |
if (loading) return <p>Loading...</p>; | |
if (error) return <p>Error :(</p>; | |
if (!this.props.match.params.id) { | |
this.props.history.push( | |
"/post/" + data.allPosts.pageInfo.endCursor | |
); | |
} | |
return ( | |
<div> | |
{data.allPosts.edges.map(({ node }) => ( | |
<div key={node.id}> | |
<p id="title"> | |
<a href={node.id} ref="test">{`${node.title}`}</a> | |
</p> | |
<div | |
className="content" | |
dangerouslySetInnerHTML={{ | |
__html: node.content | |
}} | |
/> | |
</div> | |
))} | |
<button onClick={() => this.handleNext(fetchMore, data)}> | |
Next | |
</button> | |
</div> | |
); | |
}} | |
</Query> | |
); | |
} | |
} | |
export default Posts; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment