Why the event handler function cannot get the updated state object value? - javascript

Here is my code:
App.js:
import './App.css';
import { useAlarmClock } from "./useAlarmClock";
export default function App() {
const[action,data]=useAlarmClock();
let start=()=>{
action.start();
}
return (
<div className="App">
<button onClick={start}>Start Alarm Clock</button>
</div>
);
}
useAlarmClock.js
import { useReducer } from "react";
import AlarmClock from './AlarmClock';
let reducer = (state, action) => {
let result = { ...state };
console.log(action);
switch (action.type) {
case "init":
result = { "alarmClock": action.alarmClock }
break;
default: break;
}
return result
}
export function useAlarmClock() {
const [itemList, updateItemList] = useReducer(reducer, {});
let start = () => {
let alarmClock = new AlarmClock();
alarmClock.on("connectionTimeout", () => {
console.log(itemList);
})
alarmClock.start();
updateItemList({ "type": "init", alarmClock })
}
return [{
start: start
}, {
itemList
}];
}
AlarmClock.js
export default class AlarmClock {
constructor() {
let connectionTimeoutHandler;
/*=====================================================================*/
/* To configure handler for varies event */
/*=====================================================================*/
this.on = (eventType, param) => {
switch (eventType) {
case "connectionTimeout":
connectionTimeoutHandler = param;
break;
default: break;
}
};
this.start = () => {
setTimeout(() => {
connectionTimeoutHandler();
}, 5000);
}
}
}
I expect the output of the following function:
alarmClock.on("connectionTimeout", () => {
console.log(itemList);
})
should be:
{
"alarmClock":{}
}
However the actual result is as the following:
{}
So, I don't know why the console.log output does not contain the alarmClock object.

At each render a new object for itemList is created due immutability, but you have only link to the first instance of itemList in your 'connectionTimeout' callback. You can access needed version of itemList with ref hook, so you need to do smtn like this:
useAlarmClock.js
import { useReducer } from "react";
import AlarmClock from './AlarmClock';
let reducer = (state, action) => {
let result = { ...state };
console.log(action);
switch (action.type) {
case "init":
result = { "alarmClock": action.alarmClock }
break;
default: break;
}
return result
}
export function useAlarmClock() {
const [itemList, updateItemList] = useReducer(reducer, {});
const itemListRef = useRef(itemList);
itemListRef.current = itemList;
let start = () => {
let alarmClock = new AlarmClock();
alarmClock.on("connectionTimeout", () => {
console.log(itemListRef.current);
})
alarmClock.start();
updateItemList({ "type": "init", alarmClock })
}
return [{
start: start
}, {
itemList
}];
}
UPD: here is working example:
const {useReducer, useEffect, useRef} = React;
function App() {
const[action,data]=useAlarmClock();
let start=()=>{
action.start();
}
return (
<div className="App">
<button onClick={start}>Start Alarm Clock</button>
</div>
);
}
let reducer = (state, action) => {
let result = { ...state };
console.log(action);
switch (action.type) {
case "init":
result = { "alarmClock": action.alarmClock }
break;
default: break;
}
return result
}
function useAlarmClock() {
const [itemList, updateItemList] = useReducer(reducer, {});
const itemListRef = React.useRef(itemList);
itemListRef.current = itemList;
let start = () => {
let alarmClock = new AlarmClock();
alarmClock.on("connectionTimeout", () => {
console.log(itemListRef.current);
})
alarmClock.start();
updateItemList({ "type": "init", alarmClock })
}
return [{
start: start
}, {
itemList
}];
}
class AlarmClock {
constructor() {
let connectionTimeoutHandler;
/*=====================================================================*/
/* To configure handler for varies event */
/*=====================================================================*/
this.on = (eventType, param) => {
switch (eventType) {
case "connectionTimeout":
connectionTimeoutHandler = param;
break;
default: break;
}
};
this.start = () => {
setTimeout(() => {
connectionTimeoutHandler();
}, 5000);
}
}
}
ReactDOM.render(<App />,
document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related

converting class to hooks getting messages

i'm new to react hooks, here i have been converting my project to hooks from classes, i'm getting this kind of message 'Error: Server error
at build_error (actions.js:57)
at eval (actions.js:83)' and 'GET http://127.0.0.1:8000/api/kamera/undefined 404 (Not Found)'
those errors come when i'm changing class to hooks (everything is set correcly using useState and useEffect), any idea ?
class:
initializeCollapses() {
const data = this.props[this.props.action];
let collapseStates = this.state.collapseStates;
if (!data || data.length < 1) {
return;
}
data.map((el) => {
collapseStates["" + el.name + el.identifier] = false;
return;
});
this.setState({
...this.state,
collapseStates: collapseStates,
});
}
componentDidMount() {
this.props.getItems[this.props.action](this.state.actionArgs).then(() => {
this.initializeCollapses();
});
}
Hooks:
const initializeCollapses = () => {
const data = [action];
if (!data || data.length < 1) {
return;
}
data.map((el) => {
collapseStates["" + el.name + el.identifier] = false;
return;
});
setCollapseStates(collapseStates);
};
useEffect(() => {
getItems[action](actionArgs).then(() => {
initializeCollapses();
});
}, []);
initializeCollapses() {
const data = this.props[this.props.action];
let collapseStates = this.state.collapseStates;
if (!data || data.length < 1) {
return;
}
data.map((el) => {
collapseStates["" + el.name + el.identifier] = false;
return;
});
this.setState({
...this.state,
collapseStates: collapseStates,
});
}
componentDidMount() {
this.props.getItems[this.props.action](this.state.actionArgs).then(() => {
this.initializeCollapses();
});
}
const mapDispatchToProps = (dispatch) => {
return {
getItems: {
analysers: (site) => dispatch(getAnalysers(site)),
platforms: (site) => dispatch(getPlatforms(site)),
brokers: (site) => dispatch(getBrokers(site)),
cameras: (site) => dispatch(getCameras(site)),
sites: (site) => dispatch(getSites())
},
};
};
The above class implementation in hooks would roughly be as below
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import getItems from "./store/actions";
or
import { cameras, sites, platform, brokers } from "./store/actions";
const actionArgs = useSelector(state => state.actionArgs); // In place of mapStateToProps
const dispatch = useDispatch();
useEffect(() => {
dispatch(getItems.cameras(actionArgs)) or dispatch(cameras(actionArgs)) //If destructured
}, []);
I have provided an understandable example with whatever data you provided. Refer this for a completely different approach or this one for the same mapDispatchToProps approach.
Good to refer
Example:
import React, {useReducer} from 'react';
const init = 0;
const myReducer = (state, action) => {
switch(action.type){
case 'increment':
return state + 1 // complex actions are kept in seperate files for better organised, clean code
case 'decrement':
return state - 1
case 'reset': // action types as well are kept as selectors
return init
default:
return state
}
};
function ReducerExample(){
const [count, dispatch] = useReducer(myReducer, init)
const add = () => {
dispatch({type: 'increment'})
}
const sub = () => {
dispatch({type: 'decrement'})
}
const reset = () => {
dispatch({type: 'reset'})
}
return (
<div>
<h4>Count: {count}</h4>
<button onClick={add} style={{margin: '10px'}}>Increment</button>
<button onClick={sub}>Decrement</button>
<button onClick={reset} style={{margin: '10px'}}>Reset</button>
</div>
)
}
export default ReducerExample;

Reactjs custom hook won't fire using an if/else in useEffect?

I extracted my reducer function in a custom hook. When I try to fire decreaseMinutes from the custom hook nothing happens. The other functions of the hook work great tough - such as toggleActive- (probably because they are in an event handler).
Any idea how I can solve this?
Reducer + Hook Component:
import { useReducer } from "react";
import { defaultState } from "../setDefaultState";
const DECREASE_MINUTES = "decrease minutes";
const DECREASE_SECONDS = "decrease seconds";
const TOGGLE_ISACTIVE = "toggle isActive";
const RESET = "handle reset";
export const timerReducer = (state, action) => {
switch (action.type) {
case DECREASE_SECONDS:
console.log("decrease sec works");
return {
...state,
seconds: state.seconds - 1,
};
case DECREASE_MINUTES:
return { ...state, minutes: state.minutes - 1, seconds: 59 };
case TOGGLE_ISACTIVE:
return { ...state, isActive: !state.isActive };
case RESET:
return {
...state,
seconds: action.payloads.seconds,
minutes: action.payloads.minutes,
isActive: !state.isActive,
};
default:
return state;
}
};
//extracted custom Hook
export function useTimer() {
const [timerState, dispatch] = useReducer(timerReducer, defaultState);
const decreaseSeconds = () => dispatch({ type: DECREASE_SECONDS }, console.log("decrease hook works"));
const decreaseMinutes = () => dispatch({ type: DECREASE_MINUTES });
const toggleActive = () => dispatch({ type: TOGGLE_ISACTIVE });
const reset = () =>
dispatch({
type: RESET,
payloads: {
seconds: defaultState.seconds,
minutes: defaultState.minutes,
isActive: !state.isActive,
},
});
return {
timerState,
decreaseMinutes,
decreaseSeconds,
toggleActive,
reset,
};
}
Main Component:
const Timer = () => {
const { timerState, decreaseMinutes, decreaseSeconds, toggleActive, reset } = useTimer();
const [dateState, dispatchDate] = useReducer(dateReducer, defaultState);
useEffect(() => {
let interval = null;
// reduce seconds and minutes by 1
if (timerState.isActive) {
interval = setInterval(() => {
if (timerState.seconds > 0) {
decreaseSeconds; //--> this is what I'm trying to fire
console.log("conditional works");
} else if (timerState.seconds === 0) {
if (timerState.minutes === 0) {
clearInterval(interval);
} else {
decreaseMinutes;
}
}
}, 1000);
return () => clearInterval(interval);
}
}, [timerState.isActive, timerState.seconds, timerState.minutes]);
You need to call it. Since you defined them as function. Like following:
decreaseMinutes();
decreaseSeconds();

Get the EditorState(DraftJS) from DB with Redux

I want to repopulate the editor's state with the values i have saved to Firebase.
OnSubmit:
sendNotes = (e) => {
e.preventDefault();
let contentState = this.state.editorState.getCurrentContent()
let note = { content: convertToRaw(contentState) }
note["content"] = JSON.stringify(note.content);
this.props.createNote(note.content);
};
NoteAction:
export function getNote() {
return (dispatch) => {
database.on("value", (snapshot) => {
dispatch({
type: LOAD_NOTE,
payload: snapshot.val(),
});
});
};
}
noteReducer:
export default function (state = {}, action) {
switch (action.type) {
case LOAD_NOTE:
return action.payload;
default:
return state;
}
}
REDUX/firebase:
{
type: 'LOAD_NOTE',
payload: {
'-MNOwBIWNqY_ZFDO4ILs': '{"blocks":[{"key":"c27el","text":"ASD!!!!!!!!!!!!","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}',
'-MNOyHLvaORxEmuuJmzJ': '{"blocks":[{"key":"c27el","text":"HELLO WORLD","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}',
'-MNOyP50oGHRLiP3T5_h': '{"blocks":[{"key":"c27el","text":"This is a REDUX STORE","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}'
}
}
MapStateToProps:
function mapStateToProps(state, ownProps) {
return {
note: state.notes,
};
}
export default connect(mapStateToProps, { getNote })(TextEditor);
My Code:
componentDidMount() {
this.props.getNote();
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.note !== null) {
let item = "";
_.map(nextProps.note, (note, key) => {
return (item = note);
});
this.setState({
editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(item))),
});
}
};
The code is working but I'm not 100% sure about these lifecycle methods & if the code i have written is 'stable'. I am stuck with this, please :).

React component not re-rendering on state change due to Memoize

I'm using memoize-one on a React component that is basically a table with a rows that can be filtered.
Memoize works great for the filtering but when I want to insert a new row, it won't show up on the table until I either reload the page or use the filter.
If I check the state, the new row's data is in it, so presumably what is happening is that memoize is not allowing the component to re-render even if the state has changed.
Something interesting is that the Delete function works, I am able to delete a row by removing its data from the state and it will re-render to reflect the changes...
Here's the part of the code I consider relevant but if you would like to see more, let me know:
import React, { Component } from "react";
import memoize from "memoize-one";
import moment from "moment";
import {
Alert,
Card,
Accordion,
Button,
Table,
Spinner,
} from "react-bootstrap";
import PropTypes from "prop-types";
import { getRoleMembersDetailed } from "../libs/permissions-manager-client-v1.0";
import RoleMember from "./RoleMember";
import CreateMemberModal from "./CreateMemberModal";
class RoleContainer extends Component {
filter = memoize((roleMembers, searchValue, searchCriterion) => {
const searchBy = searchCriterion || "alias";
return roleMembers.filter((item) => {
if (item[searchBy]) {
if (searchValue === "") {
return true;
}
const value = searchValue.toLowerCase();
if (searchBy !== "timestamp") {
const target = item[searchBy].toLowerCase();
return target.includes(value);
}
// Case for timestamp
const target = moment(Number(item[searchBy]))
.format("MMM DD, YYYY")
.toLowerCase();
return target.includes(value);
}
return false;
});
});
constructor(props) {
super(props);
this.state = {
collapsed: true,
roleAttributes: [],
roleMembers: [],
isLoading: true,
};
}
componentDidMount = async () => {
const roleMembers = Object.values(await this.fetchRoleMembers());
roleMembers.forEach((e) => {
e.alias = e.alias.toLowerCase();
return null;
});
roleMembers.sort((a, b) => {
if (a.alias < b.alias) {
return -1;
}
if (a.alias > b.alias) {
return 1;
}
return 0;
});
// TODO - This logic should be replaced with an API call that describes the roleAttributes.
let roleAttributes = Object.values(roleMembers);
roleAttributes = Object.keys(roleAttributes[0]);
this.setState({
roleMembers,
roleAttributes,
isLoading: false,
});
};
fetchRoleMembers = async () => {
const { roleAttributeName } = this.props;
return getRoleMembersDetailed(roleAttributeName);
};
createRoleMember = (newRoleMembers) => {
const { roleMembers } = this.state;
newRoleMembers.forEach((e) => {
roleMembers.push(e);
});
this.setState(
() => {
roleMembers.sort((a, b) => {
if (a.alias < b.alias) {
return -1;
}
if (a.alias > b.alias) {
return 1;
}
return 0;
});
return { roleMembers };
},
() => {
console.log("sss", this.state);
}
);
};
deleteRoleMember = (alias) => {
this.setState((prevState) => {
const { roleMembers } = prevState;
return {
roleMembers: roleMembers.filter((member) => member.alias !== alias),
};
});
};
render() {
const {
role,
roleAttributeName,
searchValue,
searchCriterion,
userCanEdit,
} = this.props;
const { collapsed, isLoading, roleAttributes, roleMembers } =
this.state;
const filteredRoleMembers = this.filter(
roleMembers,
searchValue,
searchCriterion
);
return (
// continues...
I don't know if it's obvious but there are two functions called filter: this.filter that belongs to memoize and Array.prototype.filter().
I did look around and found these post that says Memoize can be overridden:
If you’ve ran into a UI bug, it is simple to just return false from myComparison to temporarily override the memoization, forcing a refresh on every re-render and returning to the default component behaviour.
But I'm not sure what they mean with "return false from component"
Here's a refactoring of your code to idiomatic React Hooks style (naturally dry-coded).
Note how filtering and sorting the role members is done using useMemo() in a way that doesn't modify state; that's because they can be always recomputed from the stateful data. So long as the useMemo()s' deps array is kept in sync (there're ESLint rules to help with this), this should work with no extra re-renders. :)
Similarly, if you use useCallback (which is a special case of useMemo), you need to keep their deps arrays in sync. If you don't use useCallback, those callbacks may cause re-renders since their identity changes per-render.
import React, { Component } from "react";
import moment from "moment";
import { getRoleMembersDetailed } from "../libs/permissions-manager-client-v1.0";
function filterRoleMembers(
roleMembers,
searchValue,
searchCriterion,
) {
const searchBy = searchCriterion || "alias";
return roleMembers.filter((item) => {
if (item[searchBy]) {
if (searchValue === "") {
return true;
}
const value = searchValue.toLowerCase();
if (searchBy !== "timestamp") {
const target = item[searchBy].toLowerCase();
return target.includes(value);
}
// Case for timestamp
const target = moment(Number(item[searchBy]))
.format("MMM DD, YYYY")
.toLowerCase();
return target.includes(value);
}
return false;
});
}
// TODO: maybe use lodash's `sortBy`?
function compareByAlias(a, b) {
if (a.alias < b.alias) {
return -1;
}
if (a.alias > b.alias) {
return 1;
}
return 0;
}
async function fetchRoleMembers(roleAttributeName) {
return getRoleMembersDetailed(roleAttributeName);
}
async function loadData(roleAttributeName) {
const roleMembers = Object.values(
await fetchRoleMembers(roleAttributeName),
);
roleMembers.forEach((e) => {
e.alias = e.alias.toLowerCase();
});
// TODO - This logic should be replaced with an API call that describes the roleAttributes.
let roleAttributes = Object.values(roleMembers);
roleAttributes = Object.keys(roleAttributes[0]);
return {
roleMembers,
roleAttributes,
};
}
const RoleContainer = ({
role,
roleAttributeName,
searchValue,
searchCriterion,
userCanEdit,
}) => {
const [collapsed, setCollapsed] = React.useState(true);
const [isLoading, setIsLoading] = React.useState(true);
const [roleAttributes, setRoleAttributes] = React.useState([]);
const [roleMembers, setRoleMembers] = React.useState([]);
React.useEffect(() => {
loadData(roleAttributeName).then(
({ roleMembers, roleAttributes }) => {
setRoleAttributes(roleAttributes);
setRoleMembers(roleMembers);
setIsLoading(false);
},
);
}, [roleAttributeName]);
const createRoleMember = React.useCallback(
(newRoleMembers) => {
const updatedRoleMembers = roleMembers.concat(newRoleMembers);
setRoleMembers(updatedRoleMembers);
},
[roleMembers],
);
const deleteRoleMember = React.useCallback(
(alias) => {
const updatedRoleMembers = roleMembers.filter(
(member) => member.alias !== alias,
);
setRoleMembers(updatedRoleMembers);
},
[roleMembers],
);
const filteredRoleMembers = React.useMemo(
() =>
filterRoleMembers(roleMembers, searchValue, searchCriterion),
[roleMembers, searchValue, searchCriterion],
);
const sortedRoleMembers = React.useMemo(
() => [].concat(filteredRoleMembers).sort(compareByAlias),
[filteredRoleMembers],
);
return <>{JSON.stringify(sortedRoleMembers)}</>;
};

Redux connected React component not updating on state change

Whenever my 'COLLEGE_ADDED' action is dispatched I can see the state changes in the reducer. However the update related lifecycle methods on the CollegeSearchList component and it's children aren't being called. These components aren't re-rendering presumably because of this.
I have read the docs about not mutating state and I don't think I am. Complete code can be found here https://github.com/tlatkinson/react-search-widget.
components/search/college/CollegeSearchList.js
class CollegeSearchList extends Component {
componentWillUpdate (nextProps, nextState) {
console.log(nextProps.searchItems);
console.log(nextState);
return true;
}
render () {
return (
<SearchList searchItems={this.props.searchItems} SearchListItem={CollegeSearchListItem} />
)
}
}
const mapStateToProps = (state, {id}) => {
return {
searchItems: getSearchResultsById(state.searchState, id),
SearchListItem: CollegeSearchListItem,
}
};
CollegeSearchList = connect(
mapStateToProps
)(CollegeSearchList);
reducers/search.js
const searchReducer = (searchState = [], action) => {
switch(action.type) {
case 'COLLEGE_SEARCH':
return mergeData(searchState, action, 'college', 'phrase');
case 'COLLEGE_SEARCH_SUCCESS':
return mergeData(searchState, action, 'college', 'searchResults');
case 'COLLEGE_ADDED':
return updateCollegeAdded(searchState, action.collegeId, true);
case 'COLLEGE_REMOVED':
return updateCollegeAdded(searchState, action.collegeId, false);
default:
return searchState;
}
};
export default searchReducer
const updateCollegeAdded = (searchState, collegeId, added) => {
const newState = {...searchState};
for (let id of Object.keys(newState)) {
const searchComponent = searchState[id];
if(searchComponent.searchType === 'college') {
searchComponent.searchResults.forEach(searchResult => {
if(searchResult.id === collegeId) {
searchResult.added = added;
}
});
}
}
return newState;
};
const mergeData = (data, action, searchType, propertyModified) => {
return {
...data,
[action.id]: {
searchType,
...data[action.id],
[propertyModified]: action[propertyModified],
}
};
};
actions/index.js
export const addRemoveCollege = (collegeId, collegeName, addToList) => (dispatch) => {
if (addToList) {
api.addToCollegeList(collegeId)
.then(() => {
dispatch({
type: 'COLLEGE_ADDED',
collegeId,
collegeName,
});
})
} else {
api.removeFromCollegeList(collegeId)
.then(() => {
dispatch({
type: 'COLLEGE_REMOVED',
collegeId,
collegeName,
});
})
}
};

Categories

Resources