New to React, trying to update the state which is initialized inside the new react context provider, after the API call is success. I am using React 16.3 .
Not able to update the state value, followed documented steps but still failed to achieve.
This is what I tried:
HTML:
<MyProvider>
<MyConsumer>
{context => (
{context.updateInitialData(this.props)}
)}
</MyConsumer>
</MyProvider>
js:
import React, { Component } from 'react';
const MyContext = React.createContext();
export const MyConsumer = HeaderContext.Consumer;
export class MyProvider extends Component {
state = {
data: null,
updateInitialData: this.updateInitialData
};
updateInitialData = () => {
this.setState({data: this.state.data})
}
render() {
return (
<MyContext.Provider
value={{
state: this.state,
updateInitialData: this.updateInitialData
}}
>
{this.props.children}
</MyContext.Provider>
);
}
}
The problem is that now even if you, correctly set the state using updateInitialData, you are actually calling the function in render which will then call setState triggering a re-render and continuing the cycle. What you need is instead to write the HOC and update the initialData in lifecycle method
import React, { Component } from 'react';
const MyContext = React.createContext();
export const MyConsumer = MyContext.Consumer;
export class MyProvider extends Component {
// you don't need to store handler in state since you are explicitly passing it as a context value
state = {
data: null
};
updateInitialData = (data) => { // getting data from passed value
this.setState({data: data})
}
render() {
return (
<MyContext.Provider
value={{
state: this.state,
updateInitialData: this.updateInitialData
}}
>
{this.props.children}
</MyContext.Provider>
);
}
}
HOC:
const withContext = (Component) => {
return class App extends React.Component {
render() {
return (
<MyConsumer>
{context => (<Component {...this.props} context={context} />)}
</MyConsumer>
)
}
}
}
and then you would use it like
class Consumer extends React.Component {
componenDidMount() {
this.props.context.updateInitialData(this.props.data);
}
render() {
}
}
export default withContext(Consumer);
and thne
<MyProvider>
<Consumer data={this.props}/>
</MyProvider>
I'm not sure whether you copy-pasted it wrong but you don't update your state with data provided to the handler:
updateInitialData = () => {
this.setState({data: this.state.data}) // ??? its doing nothing
}
try:
updateInitialData = (data) => {
this.setState({ data })
}
Related
Next-Auth has the following example which is great for functions, however I have a class which I need to run const { data: session } = useSession() in it. I am wondering how can I convert it to make it valid in a class?
export default function AdminDashboard() {
const { data: session } = useSession()
// session is always non-null inside this page, all the way down the React tree.
return "Some super secret dashboard"
}
AdminDashboard.auth = true
I tried to add session: useSession() to the following constructor but it did not work.
My Class
export default class AdminDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
areas:[],
areasid:[],
users: [],
isLoading: true,
isAreaLoading: true,
session: useSession() // THIS DID NOT WORK
};
this.checkAnswer = this.checkAnswer.bind(this);
}
}
AdminDashboard.auth = true
based on the answer below. I changed the script to be like this
const withSession = (Component) => (props) => {
const session = useSession()
// if the component has a render property, we are good
if (Component.prototype.render) {
return <Component session={session} {...props} />
}
// if the passed component is a function component, there is no need for this wrapper
throw new Error(
[
"You passed a function component, `withSession` is not needed.",
"You can `useSession` directly in your component.",
].join("\n")
)
}
export default class NewCampaign extends React.Component {
render(){
const { data: session, status } = this.props.session;
const { isLoading, users, areas, areasid, isAreaLoading } = this.state;
return (
<React.Fragment></React.Fragment>
)}
}
const ClassComponentWithSession = withSession(NewCampaign)
NewCampaign.auth = false;
NewCampaign.getLayout = function getLayout(page) {
return (
<Dashboard>
{page}
</Dashboard>
)
}
However, I am getting Cannot destructure property 'data' of 'this.props.session' as it is undefined.
You should use getSession and just await the result.
async function myFunction() {
const session = await getSession()
// session available here
}
You can use it both on client and the server.
If you want to use the useSession() hook in your class components you can do so with the help of a higher order component or with a render prop.
Higher Order Component
import { useSession } from "next-auth/react"
const withSession = (Component) => (props) => {
const session = useSession()
// if the component has a render property, we are good
if (Component.prototype.render) {
return <Component session={session} {...props} />
}
// if the passed component is a function component, there is no need for this wrapper
throw new Error(
[
"You passed a function component, `withSession` is not needed.",
"You can `useSession` directly in your component.",
].join("\n")
)
}
// Usage
class ClassComponent extends React.Component {
render() {
const { data: session, status } = this.props.session
return null
}
}
const ClassComponentWithSession = withSession(ClassComponent)
Render Prop
import { useSession } from "next-auth/react"
const UseSession = ({ children }) => {
const session = useSession()
return children(session)
}
// Usage
class ClassComponent extends React.Component {
render() {
return (
<UseSession>
{(session) => <pre>{JSON.stringify(session, null, 2)}</pre>}
</UseSession>
)
}
}
Ok so I am trying to understand React Hooks and how to update
my code to grab the JSON from the source below and show the data. I'm clear on importing the hook and initializing it with useState(0) but my code fails when I try to re-factor within my fetch statement. Any/all help would be greatly appreciated...see below.
// import React, { Component } from 'react';
import React, { useState } from 'react';
import Feeder from './Feeder';
import Error from './Error';
// class NewsFeeder extends Component {
// constructor(props) {
// super(props);
// this.state = {
// news: [],
// error: false,
// };
// }
const [hideNews,showNews] = useState(0);
componentDidMount() {
const url = `https://newsfeed.com`;
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
this.setState({
news: data.articles
})
})
.catch((error) => {
this.setState({
error: true
})
});
}
renderItems() {
if (!this.state.error) {
return this.state.news.map((item) => (
<FeedPrime key={item.url} item={item} />
));
} else {
return <Error />
}
}
render() {
return (
<div className="row">
{this.renderItems()}
</div>
);
}
}
export default NewsFeeder;
React hooks are created for functional components and are not ment to be used in class components.
Here is a table of the functionality and the way to achive it using classes and functions with hooks.
component type
state
fetch
class
store the state in this.state that you only assign once in the constructor, use this.setState to modify the state
do your fetch logic in componentDidMount
function
create a pair of [example, setExample] with useState
do fetch in useEffect hook
Using fetch with hooks: (edited version of this):
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await fetch('https://hn.algolia.com/api/v1/search?query=redux').then(response => response.json());
setData(result);
});
let items = data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
));
return (
<ul>
{items}
</ul>
);
}
export default App;
I have functional component wrapped with HOC. Its returns some props after api call. How do I set the state in my child component(functional).
const withEditHoc = (WrappedComponent, actioneffects) => {
class HOC extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
};
}
executeAllActions = async (data, id) => {
await Promise.all(data.map(act => this.props.dispatch(act(id)))).then(() =>
this.setState({ loading: false }),
);
};
componentDidMount = () => {
const editpageId = this.props.match.params.id;
this.executeAllActions(actioneffects, editpageId);
};
render() {
console.log(this.state.loading);
return (
<React.Fragment>
<Loading loading={this.state.loading}>
<WrappedComponent {...this.props} />
</Loading>
</React.Fragment>
);
}
}
return HOC;
This is my HOC Structure. After the api call the data will be in redux.
I am getting a prop for my functional component using mapToStateProp.(react version 16.3)
Please any suggestion for this.
Functional component
function ProjectDetails(props) {
const [projectValue, setValue] = useState({});
const [proData, setProData] = useState({ ...props.project });
useEffect(() => {
setProData({ props.project });//Here I need to set my data, Iam not able to set data here.
}, []);
return <div>{JSON.stringify(props.project)}</div>;
}
function mapStateToProps(state) {
return {
project: state.projects.project,
};
}
const projectDetailsWithHocLoading = withEditHoc(ProjectDetails, [actions.apiCall()]);
export default connect(mapStateToProps, null)(projectDetailsWithHocLoading);
I am a beginner to react. Please suggest a good way
mapStateToProps created for class components.
because you are using hooks, you should use useSelector hook
import { useSelector } from 'react-redux';
function ProjectDetails(props) {
const [projectValue, setValue] = useState({});
const proData = useSelector(state => state.projects.project)
return <div>{JSON.stringify(proData)}</div>;
}
const projectDetailsWithHocLoading = withEditHoc(ProjectDetails,actions.apiCall()]);
export default projectDetailsWithHocLoading;
I have a component which is using redux connect. In this component I have mapStateToProps which getting project from redux state and projectTransform is a value which has filter values from project redux state:
import React, { Component } from 'react';
import PropTypes from "prop-types";
import { connect } from 'react-redux';
class ProjectForm extends Component {
constructor(props){
super(props);
}
componentDidMount() {
const {
fetchProject,
} = this.props;
fetchProject();
}
onClick() {
this.setState({
project1: {
"a": 1,
"b": 2
}
})
}
render() {
const { project1 } = this.props;
return (
<div>
<button onClick={onClick()} />
</div>
)
}
}
ProjectForm.propTypes = {
fetchProject: PropTypes.func.isRequired
};
function mapDispatchToProps (dispatch) {
return
fetchProject: () => dispatch(projectActions.getProjectRequest()),
}
}
function mapStateToProps ( state ) {
const { project} = state
return {
project: project,
project1: ((project) => {
return project[0]
})(project)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ProjectForm)
I trying to now trigger re-rendering on the button but I have not clue how to do it as I tried.
this.setState((previousState) => {
project1: [JSON value from Form]
});
Also why previousState is null I would assume it would have mapStateToProps data.
Any idea how to do it without dispatching whole redux? Or how to do it in a proper way?
The problem was with reading data not from the state but props.
render() {
const { project1 } = this.state;
return (
<div>
<button onClick={onClick()} />
</div>
)
}
I'm using react-lifecycle-component in my react app, and incurred in this situation where I need the componentDidMount callback to load some data from the backend. To know what to load I need the props, and I can't find a way to retrieve them.
here's my container component:
import { connectWithLifecycle } from "react-lifecycle-component";
import inspect from "../../../libs/inspect";
import fetchItem from "../actions/itemActions";
import ItemDetails from "../components/ItemDetails";
const componentDidMount = () => {
return fetchItem(props.match.params.number);
};
// Which part of the Redux global state does our component want to receive as props?
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
};
};
// const actions = Object.assign(locationActions, lifecycleMethods);
export default connectWithLifecycle(mapStateToProps, { componentDidMount })(
ItemDetails
);
Any clues?
thanks.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import fetchItem from '../actions/itemActions'
class Container extends Component {
state = {
items: []
}
componentDidMount() {
const { match } = this.props
fetchItem(match.params.number)
// if your fetchItem returns a promise
.then(response => this.setState({items: response.items}))
}
render() {
const { items } = this.state
return (
<div>
{ items.length === 0 ? <h2>Loading Items</h2> :
items.map((item, i) => (
<ul key={i}>item</ul>
))
}
</div>
)
}
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
}
}
export default connect(mapStateToProps)(Container)
Though I don't see where you are using the props you take from your Redux store...