Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have 10 reducer and I want to delete state values in every reducer with
a single click, how can I achieve this?
I think the most straight forward way to reset history would be to create an action that the 10 reducers listen for and when it occurs they reset their state accordingly. Here is an example:
class ResetState extends Action {
readonly type = "RESET_STATE"
}
reducer 1
function reducer1(state, action){
switch(action.type) {
case "RESET_STATE":
return {};
}
}
reducer 2
function reducer2(state, action){
switch(action.type) {
case "RESET_STATE":
return {
someCount: 0,
someArray: [],
someBoolean: false,
};
}
}
You can create a metaReducer like so.
export function clearData(reducer: ActionReducer<any>): ActionReducer<any> {
return function (state, action) {
switch (action.type) {
case CLEAR_DATA:
state = undefined;
}
return reducer(state, action);
};
}
and include it in your metaReducers array which will be finally fed to StoreModule initialisation in your feature modules.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 days ago.
Improve this question
I'm trying to find the best way to create and update items in a list. So, I have a form with item fields and I have the idea to provide a function (update or create) depending on the mode I choose. For example, I click the edit button and set the "update" mode, or I click the "add new item" button and set the "create" mode. In this case I don't need to add two identical components with different click handlers (one for update, one for create), I will just provide a click handler depending on the mode state.
What do you think about this implementation?
import {useState} from "react";
enum MODES {
view= "view",
update= "update",
create= "create",
}
const Page = () => {
const [mode, setMode] = useState<MODES>(MODES.view);
const [clickHandler, setClickHandler] = useState<() => void>();
const [item, setItem] = useState({});
const updateHandler = () => {};
const createHandler = () => {};
const setModeHandler = (mode: MODES) => {
switch (mode) {
case MODES.update: {
setItem(selectedItem);
setClickHandler(updateHandler);
} break;
case MODES.create: {
setItem({});
setClickHandler(createHandler);
} break;
default: {
} break;
}
}
return (
<div>
<div>
<button onClick={() => {setModeHandler(MODES.update)}}>update</button>
<button onClick={() => {setModeHandler(MODES.create)}}>create</button>
</div>
<ItemModal click={clickHandler} item={item} />
</div>
)
}
I attached the draft to better understand my question.
I would be glad to hear your opinion on this matter.
What do you think about this idea?
Is it okay or better to use to components with different handlers?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I have this code which goes and get the data from API,
const getDevices = async () => {
const response = await fetch(`${API_URL}`);
const json = await response.json();
setData(json);
for (let i in json) {
Object.values(json[i].portOn.split(",")).forEach((value) => {
if (value === "G01") {
blinkStatus = "blink_me";
}
}
and also I have this in return which is supposed to change the className:
<div id="portG01" className={blinkStatus}></div>
But it doesn't work. the DIV doesn't get the className. No error at all.
I am trying to read the data from database and then change the className according to the data.
This is what I need as result:
<div id="portG01" className="blinkStatus"></div>
You need to have blinkStatus changing trigger a rerender of the component. To do this, you can use state. So you can do:
import React, { useEffect, useState } from "react";
...
const [blinkStatus, setBlinkStatus] = useState();
// useEffect(() => {}, []) is the equivalent of the old componentDidMount
useEffect(() => {
const value = await ... // get blink status
setBlinkStatus(value);
}, []);
...
return (
<div className={blinkStatus}>
...
</div>
);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I use a button to control the audio player mute but it makes the player default mute, I want that only mute when clicking.How to edit it
import React, { useState } from "react";
import ReactAudioPlayer from "react-audio-player";
const Test = () => {
const [ismute, setOpen] = useState(false);
return (
<><div>
<ReactAudioPlayer
controls
muted={ismute ? "false": "True"}
src='https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'
loop
autoPlay
/>
</div><button onClick={() => setOpen(!ismute)}>click me!</button>
</>
);
};
export default Test
If you are passing as string,
muted={ismute ? "false": "True"}
since the initial value of the ismute is false as:
const [ismute, setMute] = useState(false);
then what you are going to pass as a prop is True or false which is truthy value which makes ismute as always mute
For state ismute, initially assign value true instead of false as below:
const [ismute, setOpen] = useState(true);
You should pass muted prop as either true or false. You are passing as a string
muted={ismute ? false: true }
I've created a simulation for player
For state ismute, initially assign value true instead of false as below:
const [ismute, setOpen] = useState(true);
Another correction might be at component ReactAudioPlayer:
<ReactAudioPlayer
controls
muted={ismute}
src='https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'
loop
autoPlay
/>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to fetch data, get it to state and then modify it
state = {
data: []
}
I have this state with an empty array, then I fetching data from API
constructor(){
super();
this.getItem();
}
getItem(){
this.service
.mergeData()
.then((body) => {
this.setState({
data: body.map(product => product),
})
})
}
And then I am trying to use this data from state:
dataToFilter = this.state.data.map((e) => {
return e;
})
But the problem is dataToFilter is empty because the state is empty
How can I solve this?
Edit: OP asked the below question, so I have updated my StackSnippet to reflect this question.
I need to use data in the state not in the render function but in the component after the componentDidMount. Am I able to do that?
If you want to load data after the component mounts, you can use the componentDidMount life cycle method. You can read more on life cycle methods here and here.
Furthermore, you will need to use an arrow function with getItem() if you are not binding the method inside the constructor..
CodePen showing how to use a class method in the constructor via an arrow function.
CodePen showing how to use a class method without an arrow function, using bind, in the constructor.
Here is how you can use componentDidMount to retrieve API data:
CodePen Mirror
class ApiFetcher extends React.Component {
state = {
apiData: "",
id: 1
};
componentDidMount() {
this.getNextFromApi();
}
getNextFromApi = () => {
fetch(`https://jsonplaceholder.typicode.com/todos/${this.state.id}`)
.then(response => response.json())
.then(json => {
this.setState({
id: this.state.id + 1,
apiData: json
}, () => {
// After you set your state,
// you can use the callback that `setState` provides
this.doSomethingWithData();
});
});
}
doSomethingWithData = () => {
// Here is where you can do something with the data
this.setState({ message: 'Check your console!' });
console.log("I am doing something with the data!", this.state.apiData);
// Do whatever you need to here
}
render() {
return (
<div>
{this.state.message ? <p>{this.state.message}</p> : ""}
<hr /><br /><br />
<h3>Just pretend this does not exist, if you do not want to display data here</h3>
<button onClick={this.getNextFromApi}>Next Result</button>
{this.state.apiData ? (
<pre>{JSON.stringify(this.state.apiData, null, 2)}</pre>
) : (
<p>Unable to get data..</p>
)}
</div>
);
}
}
class App extends React.Component {
render() {
return <ApiFetcher />;
}
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I think it's better, you use componentwillupdate method for call dataToFilter.
Or
This code call in render method.
dataToFilter = this.state.data.map((e) => {
return e;})
What is the consensus on an action affecting multiple parts of the state tree in Redux?
For example:
const ADD_POST = 'POST/ADD';
function postsReducer(state = initialState, action = {}) {
// switch ...
case ADD_POST:
return {
...state,
...action.result.post
}
}
function anotherReducer(state = initialState, action = {}) {
// switch ...
case ADD_POST:
return {
...state,
post_id: action.result.post.id
}
}
I'm seeking advice on:
Actions affecting multiple parts of the redux store/state
Yes, absolutely. It’s the whole reason why actions exist: to separate what happened from the component’s point of view from what actually happens in terms of state change.
Yes, it's ok. If that's what you want to happen.