Dynamically update value based on State in React - javascript

I have a react class based component where I have defined a state as follows:
class MyReactClass extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedDataPoints: new Set()
};
}
// This method is called dynamically when there is new addition of data
storeData = (metricName, dataPoint) => {
if (this.state.selectedDataPoints.has(dataPoint)) {
this.state.selectedDataPoints.delete(dataPoint);
} else {
this.state.selectedDataPoints.add(dataPoint);
}
};
render () {
return (
<p>{this.state.selectedDataPoints}</p>
);
}
}
Note that initially, the state is an empty set, nothing is displayed.
But when the state gets populated eventually, I am facing trouble in spinning up the variable again. It is always taking as the original state which is an empty set.

If you want the component to re-render, you have to call this.setState () - function.

You can use componentshouldUpdate method to let your state reflect and should set the state using this.state({}) method.

Use this code to set state for a set:
export default class Checklist extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedDataPoints: new Set()
}
this.addItem = this.addItem.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addItem(item) {
this.setState(({ selectedDataPoints }) => ({
selectedDataPoints: new Set(selectedDataPoints).add(item)
}));
}
removeItem(item) {
this.setState(({ selectedDataPoints }) => {
const newSelectedDataPoints = new Set(selectedDataPoints);
newSelectedDataPoints.delete(item);
return {
selectedDataPoints: newSelectedDataPoints
};
});
}
getItemCheckedStatus(item) {
return this.state.checkedItems.has(item);
}
// This method is called dynamically when there is new addition of data
storeData = (metricName, dataPoint) => {
if (this.state.selectedDataPoints.has(dataPoint)) {
this.state.selectedDataPoints.removeItem(dataPoint);
} else {
this.state.selectedDataPoints.addItem(dataPoint);
}
};
render () {
return (
<p>{this.state.selectedDataPoints}</p>
);
}
}

Related

How to inject functions that change component state?

I want to keep some functions outside of my component for easier testing. However, I cannot change state with these functions because they cannot reference the component's state directly.
So I currently have the hacky solution where I set the function to a variable then call this.setState. Is there a better convention/more efficient way to do this?
Example function code in Tester.js:
const tester = () => {
return 'new data';
}
export default tester;
Example component code in App.js (without imports):
class App extends Component {
constructor() {
super();
this.state = {
data: ''
}
}
componentDidMount(){
let newData = tester();
this.setState({ data: newData })
}
render() {
return(
<div>{this.state.data}</div>
)
}
}
You could bind your tester function like this (this approach doesn't work with arrow functions):
function tester() {
this.setState({ data: 'new Data' });
}
class App extends Component {
constructor() {
super();
this.state = {
data: '',
};
this.tester = tester.bind(this);
}
componentDidMount() {
this.tester();
}
render() {
return (
<div>{this.state.data}</div>
);
}
}
But I would prefer a cleaner approach, where you don't need your function to access this (also works with arrow functions):
function tester(prevState, props) {
return {
...prevState,
data: 'new Data',
};
}
class App extends Component {
constructor() {
super();
this.state = {
data: '',
};
}
componentDidMount() {
this.setState(tester);
}
render() {
return (
<div>{this.state.data}</div>
);
}
}
You can pass a function to setState() that will return a new object representing the new state of your component. So you could do this:
const tester = (previousState, props) => {
return {
...previousState,
data: 'new data',
};
}
class App extends Component {
constructor() {
super();
this.state = {
data: ''
}
}
componentDidMount(){
this.setState(tester)
}
render() {
return(
<div>{this.state.data}</div>
)
}
}
The reason being that you now have access to your component's previous state and props in your tester function.
If you just need access to unchanging static placeholder values inside of your app, for example Lorem Ipsum or something else, then just export your data as a JSON object and use it like that:
// testData.js
export const testData = {
foo: "bar",
baz: 7,
};
...
// In your app.jsx file
import testData from "./testData.js";
const qux = testData.foo; // "bar"
etc.

Can i have a function inside a state in react?

I'm trying to create variables and a function inside a state like this
state = {
modalVisible: false,
photo:""
getDataSourceState
}
which i have done, how can i call the function outside the state and set a new state.
This what i have done but i keep getting errors
getDataSourceState() {
return {
dataSource: this.ds.cloneWithRows(this.images),
};
}
this.setState(this.getDataSourceState());
see what prompted me to ask the question, because i was finding it difficult to access modalVisible in the state since there is a this.state = this.getDataSource()
constructor(props) {
super(props);
this.state = {
modalVisible: false,
photo:"",
sourceState: getDataSourceState()
}
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.lastPhotoFetched = undefined;
this.images = [];
this.fetchPhotos();
this.getDataSourceState = this.getDataSourceState.bind(this)
}
componentDidMount(){
this.getDataSourceState();
}
getDataSourceState() {
return {
dataSource: this.ds.cloneWithRows(this.images),
};
}
getPhotosFromCameraRollData(data) {
return data.edges.map((asset) => {
return asset.node.image;
});
}
}
You can't the way you have attempted but technically yes, you can have a function that returns the desired state you want initialised in your constructor. I wouldn't suggest doing it though.
You will quickly run into issues where your components aren't updating state correctly.
What you are looking for is a function that returns a value as opposed to sets state. You would do something like this:
constructor(){
super()
this.state = {
modalVisible: false,
photo:""
sourceState: this.getDataSourceState()
}
this.getDataSourceState = this.getDataSourceState.bind(this)
}
getDataSourceState(){
return this.ds.cloneWithRows(this.images)
}
As I mentioned, it is not a good idea to do it this way. You are better off initialising the state values as a default value and then setting the state in your componentDidMount like so:
constructor(){
super()
this.state = {
modalVisible: false,
photo:""
sourceState: null
}
this.getDataSourceState = this.getDataSourceState.bind(this)
}
componentDidMount(){
this.getDataSourceState()
}
getDataSourceState(){
const data = this.ds.cloneWithRows(this.images)
this.setState({soureState: data})
}
This way you have a reusable function which you can call in componentDidUpdate() if need be for when you move navigate between the same component with different data and want the state to update.
Yes you can.
class App extends Component {
func1 = () => {
this.setState({flag:!this.state.flag})
}
state = {
flag:true,
doclick:this.func1
}
}

How to keep state when switch the component in Reactjs?

I have a component
class App extends React.Component {
constructor(props) {
super(props);
this.state = {stories: []};
}
componentDidMount() {
$.get(Api.getList(), (result) => {
const data = result;
if (data) {
this.setState((prevState) => ({
stories: data.stories
}));
}
});
}
render() {
if (this.state.stories.length == 0) {
return (
<Tpl>
<Loading/>
</Tpl>
);
} else {
return (
<Tpl>
<Stories stories={this.state.stories}/>
</Tpl>
);
}
}
}
and everytime when I switch to this component,
it will run constructor first.
so the state will be empty.
what I want is if stories had items, it don't need to get data again.
is it any method to keep that state?
I think the best way to achieve this would be to use react-redux whereby you have a centralized store which maintains state to all the components and thus saving it from refreshing everytime the component loads
Here is a good article to help you get started with redux.
The other way to do what you want is to have you states saved in localStorage whereby on every component load you load data from localStorage and set to state initially and when updating a state also update the value there. Below is a sample method that you can follow for this approach.
constructor(props) {
super(props);
var stories = JSON.parse(localStorage.getItem( 'stories' )) || null
this.state = {stories: stories};
}
componentDidMount() {
$.get(Api.getList(), (result) => {
const data = result;
if (data) {
JSON.stringify(localStorage.setItem( 'stories', data.stories));
this.setState((prevState) => ({
stories: data.stories
}));
}
});
}

Enzyme test issues returns undefined

I'm trying to do unit test my React class component using {mount} method. When I try to access the class variable (using this keyword), running the test gives an error of undefined. Example below where this.DataSource evaluate to undefined after calling mount(<GridComponent recordArr=[1,2,3] />
export class GridComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
pageRecords: [],
totalSize: 0
}
this.options = {
page: 1,
sizePerPage: 10
}
this.DataSource = [] //All records will be stored here
}
componentDidMount() {
this.DataSource = this.props.recordArr
this.parseProps()
}
componentWillReceiveProps(nextProps) {
this.DataSource = nextProps.recordArr
this.parseProps()
}
parseProps = () => {
let pageRecords = []
if (!_.isEmpty(this.DataSource)) { //this.DataSource ==> undefined
let startIndex = (this.options.page - 1) * this.options.sizePerPage
let count = (this.options.page - 1) * this.options.sizePerPage + this.options.sizePerPage
pageRecords = _.slice(this.DataSource, startIndex, count)
}
this.setState({
...this.state,
pageRecords: pageRecords,
totalSize: this.DataSource.length
})
}
render() {
... //Render the records from this.state.pageRecords
}
}
Change this.DataSource as a component state and then use, Enzyme util setState function: in your test case.
wrapper.setState({ DataSource: 'somesource' });
For example your components's componentWillReceiveProps method will look like this:
componentWillReceiveProps(nextProps) {
this.setState({
DataSource: nextProps.recordArr,
});
this.parseProps()
}

Why react doesn't call render when state is changed?

I have problem with automatically re-rendering view, when state is changed.
State has been changed, but render() is not called. But when I call this.forceUpdate(), everything is ok, but I think that's not the best solution.
Can someone help me with that ?
class TODOItems extends React.Component {
constructor() {
super();
this.loadItems();
}
loadItems() {
this.state = {
todos: Store.getItems()
};
}
componentDidMount(){
//this loads new items to this.state.todos, but render() is not called
Store.addChangeListener(() => { this.loadItems(); this.forceUpdate(); });
}
componentWillUnmount(){
Store.removeChangeListener(() => { this.loadItems(); });
}
render() {
console.log("data changed, re-render");
//...
}}
You should be using this.state = {}; (like in your loadItems() method) from the constructor when you are declaring the initial state. When you want to update the items, use this.setState({}). For example:
constructor() {
super();
this.state = {
todos: Store.getItems()
};
}
reloadItems() {
this.setState({
todos: Store.getItems()
});
}
and update your componentDidMount:
Store.addChangeListener(() => { this.reloadItems(); });
You sholdn't mutate this.state directly. You should use this.setState method.
Change loadItems:
loadItems() {
this.setState({
todos: Store.getItems()
});
}
More in react docs
In your component, whenever you directly manipulate state you need to use the following:
this.setState({});
Complete code:
class TODOItems extends React.Component {
constructor() {
super();
this.loadItems();
}
loadItems() {
let newState = Store.getItems();
this.setState = {
todos: newState
};
}
componentDidMount(){
//this loads new items to this.state.todos, but render() is not called
Store.addChangeListener(() => { this.loadItems(); this.forceUpdate(); });
}
componentWillUnmount(){
Store.removeChangeListener(() => { this.loadItems(); });
}
render() {
console.log("data changed, re-render");
//...
}}

Categories