I am making a page which has many editable input fields.
I am using redux-toolkit and redux-thunk for this.
I am fetching data from api and put them into redux store. First render of component I want to reflect data in the store to the component's local state so that I can edit them and onSubmit of form, I am planning to re-put new values to store again.
Is this good approach?
Now it does not render anything and I think it because component rendering before api response arrives.
Is it possible without using redux-forms?
Component
import React, { useEffect, useState } from 'react'
import { Col, Row } from 'reactstrap'
import PreviewCaseTable from './refactor/PreviewCaseTable'
import { useDispatch, useSelector } from 'react-redux'
import { fetchCases, fetchCollections } from '../../../store/case/caseSlicer'
const TaskPreview2 = (props) => {
const dispatch = useDispatch()
const TaskStore = useSelector(store => store.Task)
const CaseStore = useSelector(store => store.Case)
const [cases, setCases] = useState(CaseStore.cases)
const [collections, setCollections] = useState(CaseStore.collections)
useEffect(() => {
dispatch(fetchCases({
taskId: TaskStore.selectedTask.taskId,
page: 0,
size: 100,
taskType: TaskStore.selectedTask.taskType
}))
dispatch(fetchCollections({ taskId: TaskStore.selectedTask.taskId }))
}, [])
return (
<div className="page-content">
<Row>
<Col>
{/*<UpdateWeightCard/>*/}
</Col>
<Col>
{/*<StrategyCard/>*/}
</Col>
</Row>
<Row>
{console.log("Cases:", cases)}
{cases.length > 0 && <PreviewCaseTable
cases={cases}
collections={collections}/>}
</Row>
</div>
)
}
Related
The point is to implement a dynamic SSR component can be re-rendered by a search input.
I solved this by creating a layout.tsx file on my specific router then import children which made me dynamic render ssr component by the client component:
Layout.tsx
import React, { Suspense } from "react";
import Search from "./Search";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="layout">
<Search />
{children}
</div>
);
}
Search.tsx
"use client";
import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
export default function Search() {
const [text, setText] = useState<string>("")
const router: any = useRouter();
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setText('')
router.push(`/definition/${text}`)
}
return (
<form onSubmit={handleSubmit} className='search'>
<input onChange={(e) => setText(e.target.value)}
value={text} type="text"
placeholder={"write to search"} />
</form>
);
} );
}
import { Container } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import Layout from '../../components/Layout/Layout'
const CartScreen = () => {
const cart = useSelector(state => state.cart)
const { cartItems } = cart
console.log(cartItems)
return (
<Layout>
<Container>
<div>
<h1>Shopping Cart</h1>
{cartItems && cartItems.length === 0 && <p>Your cart is empty </p>}
</div>
</Container>
</Layout>
)
}
export default CartScreen
This code gives me that Hydration Error only when 'cart' is empty
I don't know how to use useEffect on this and I use redux toolkit.
I'm creating a website using mern stack. In react files, I'm using many hooks, in useState hook, it takes some time to change and set new state. So, for that time it's showing data before changed state. I want to give some loading effect for the time till useState change the state and show data. What is the short and simple way to create that effect?
You can use something like this
import React, { useEffect } from "react";
import { getDatas } from "./getDatas";
import Datas from "../components/Datas";
import Loading from "../components/Loading";
export default function Component() {
const [datas, setDatas] = useState();
const [loading, setLoading] = useState(true);
useEffect(() => {
getDatas().then((res) => {
setDatas(res.datas);
setLoading(false);
});
}, []);
return (
<div>
{loading ? <Loading /> : <Datas />
</div>
);
}
I'm new to react native development. And I have created this sample note application using Redux for react native. In this application user must be able to add a note and that note needs to be managed via redux store.
And I have created required action and reducer for adding note functionality.
However I was not able to add a new note to the store. I tried debugging and when it reaches the "ADD_Note" case in reducer, it jump into default case automatically. And whatever the string value or note that pass via action, it becomes 'undefined' in the reducer.
Please refer my code for adding note screen
import React, {useState, useEffect} from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
Button,
FlatList,
} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import * as NoteActions from '../store/actions/Note'; // import note actions
const NoteScreen = () => {
const [note, setNote] = useState('');
const dispatch = useDispatch(); // use dispatch
const noteHandler = text => {
setNote(text);
};
return (
<View style={styles.container}>
<View>
<TextInput
style={styles.textInput}
placeholder="Enter a note"
onChangeText={noteHandler}
value={note}
/>
<Button
title="Add"
onPress={() => {
console.log(note);
dispatch(NoteActions.addNote(note));
}}
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
margin: 10,
},
textInput: {
width: '100%',
marginBottom: 10,
textAlign: 'center',
borderBottomWidth: 1,
},
});
export default NoteScreen;
And below is the action js file.
// action types
export const ADD_NOTE = 'ADD_NOTE'
//action creators
export function addNote(note){
return{
type:ADD_NOTE,
date:note
}
}
And below is the reducer js file
// initial state
const initialState ={
noteList:[]
}
// import actions
import ADD_NOTE from '../actions/Note';
function noteReducer (state=initialState, action){
debugger;
switch(action.type){
case ADD_NOTE:
const newNote = action.data
return{
...state,
noteList: state.noteList, newNote
}
default:
return state;
}
}
export default noteReducer;
Please help me.
Thanks in advance,
Yohan
You need to add layer of dispatch at your action, also watch the typo date instead data
export const addNote = (note) => (dispatch, getState) => {
return dispatch({
type:ADD_NOTE,
data :note
})
}
I've written an action that is currently getting dispatched successfully. I can see the network request and it does return a successful response with the requested object(s), but this object is not making it back to the action. Instead its coming back in as undefined and I can't figure out why. What am I overlooking?
STORE:
import * as redux from "redux";
import thunk from "redux-thunk";
import {permitCellDesignsReducer, [other reducers her...]}
export const init = () => const reducer = redux.combineReducers({ {permitCellDesigns: permitCellDesignsReducer,...} });
const store = redux.createStore(reducer, redux.applyMiddleware(thunk));
return store;
ACTION:
export const getPermitCellDesignByFacilityId = id => {
debugger;
return dispatch => {
axios.get("/api/facilities/permits/cellDesign/" + id)
.then(res => { return res.date })
.then(cells => {
dispatch(getFacilityCellDesignsSuccess(cells));
})
}
}
const getFacilityCellDesignsSuccess = cells => {
return {
type: "GET_CELL_DESIGN_LIST",
action: cells
}
}
REDUCER:
const INITIAL_STATE = {
permitCellDesigns: {}
}
export const permitCellDesignsReducer = (state = INITIAL_STATE.permitCellDesigns, action) => {
debugger;
switch (action.type) {
case "GET_CELL_DESIGN_LIST":
return {
...state,
permitCellDesigns: action.cells
}
default:
return state
}
}
DISPATCHED ACTION:
import React from "react";
import { connect } from "react-redux";
import { Row, Col, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import FacilityHeader from '../facilities/FacilityHeader';
import * as actions from "../../actions/FacilityActions";
import * as permits from "../../actions/PermitActions";
import PermitPlanApprovalTable from './permitPlanApproval/PermitPlanApprovalTable';
import PermitCellDesignTable from './permitCellDesign/PermitCellDesignTable';
class PermitInfo extends React.Component {
componentDidMount() {
this.props.dispatch(actions.getFacilityById(this.props.id) );
this.props.dispatch(permits.getPermitPlanApprovalsByFacility (this.props.id));
this.props.dispatch(permits.getPermitCellDesignByFacilityId(this.props.id)
);
}
render() {
debugger;
const { facility, permitCellDesigns } = this.props;
if (!permitCellDesigns) {
return <div>Loading...</div>
}
return (
<div>
<FacilityHeader {...this.props} />
<Row>
<Col>
<h4>Permit/Plan Approvals</h4>
</Col>
<Col>
<Link to={{
pathname: `/facilities/permits/permitplanapproval/${this.props.id}`,
state: { facilityName: facility.facilityName }
}}><Button className="btn btn-light edit">Create</Button></Link>
</Col>
</Row>
<Row>
<Col>
<PermitPlanApprovalTable {...this.props} />
</Col>
</Row>
<Row>
<Col>
<br /><h4>Cell Design Information</h4>
</Col>
<Col>
<Link to={{
pathname: `/facilities/permits/celldesign/${this.props.id}`,
state: { facilityName: facility.facilityName }
}}><Button className="btn btn-light edit">Create</Button></Link>
</Col>
</Row>
<Row>
<Col>
<PermitCellDesignTable {...this.props} />
</Col>
</Row>
</div>
)
}
}
const mapStateToProps = state => ({
facility: state.facility.facility,
permitApprovals: state.permitApprovals.permitApprovals,
permitCellDesigns: state.permitCellDesigns.permitCellDesigns
});
export default connect(mapStateToProps)(PermitInfo);
NETWORK REQUEST RESPONSE:
ACTION RETURNED AS UNDEFINED:
All other props that were dispatched are present but not the one in question