I'm having a lot of trouble to close my Modal component once my request is done.
My method togglePop works fine with the handleClick method i have in my modal component(I did not included here).
What i m trying to do is to reverse the "Togglepop" method into the state of Modal.js. Then, setState in my axios sbmit.
Avaibaliities.js
this.state = {
showModal: false
};
}
validation = () => {
if (this.state.showDate) {
this.setState({
showModal: true
});
}
togglePop = () => {
this.setState(prevState => ({
showModal: !prevState.showModal
}));
};
render() {
{this.state.showModal && <Modal dateModal={this.state.date} toggle={this.togglePop} />} }
Modal.js
state = {
mailFilled: '',
sent: false,
showPopup: false,
closeModal: !this.props.toggle
};
handleSubmit = (event) => {
let data = {
mailFilled: this.state.mailFilled,
dateIn: dateFirst,
dateOut: dateSecond
};
axios
{
this.setState(
{
sent: true,
showPopup: true
}
)
setTimeout(() => {
this.setState({
showPopup: false
})
}, 3000);
this.setState({
showPopup: false,
closeModal: this.props.toggle
})
This is kinda new for me. I really want to understand what im a doing wrong.
Thanks in advance
Since it's a function, I think it needs to be invoked and not just referenced
this.setState({
showPopup: false,
closeModal: this.props.toggle()
});
Related
I'm converting a class component to a functional component using React Hooks and for some reason my onCancel errors with Parsing error: Unexpected token, expected ","
I'm not sure if I've done the conversion correctly.
BEFORE
class ClosedCaptions extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: props.isOpen,
};
this.handleClick = this.handleClick.bind(this);
this.onCancel = this.onCancel.bind(this);
}
componentDidMount() {
const { fetchClosedCaption, fetchPersona } = this.props;
fetchClosedCaption();
fetchPersona();
}
componentDidUpdate(prevProps) {
if (prevProps.isUpdatingPersona !== this.props.isUpdatingPersona && this.props.isUpdatingPersona) {
this.setState({
isOpen: false,
});
}
}
onCancel() {
this.setState({
isOpen: false,
});
this.props.restoreToSaved();
}
handleClick() {
this.setState({
isOpen: true,
});
}
AFTER
const ClosedCaptions = ({ isOpen, fetchClosedCaption, fetchPersona, restoreDefault }) => {
const { t } = useTranslate();
const [newIsOpen, setIsOpen] = useState(isOpen);
useEffect(() => {
fetchClosedCaption();
fetchPersona();
}, [])
useEffect(() => {
if (isUpdatingPersona !== isUpdatingPersona && isUpdatingPersona) {
setIsOpen(false);
}
}
const onCancel = () => {
setIsOpen(false);
restoreToSaved();
}
const handleClick = () => {
setIsOpen(true);
}
useEffect(() => {
if (isUpdatingPersona !== isUpdatingPersona && isUpdatingPersona) {
setIsOpen(false);
}
}
This is missing , [isUpdatingPersona]), and the const on the next line is triggering your Unexpected token error. To clarify, it should be written:
useEffect(() => {
if (isUpdatingPersona !== isUpdatingPersona && isUpdatingPersona) {
setIsOpen(false);
}
}, [isUpdatingPersona])
with isUpdatingPersona declared above rather than below in order to be referenced as a dependency of the effect.
Normally I would close this as "Not reproducible or was caused by a typo" but since I already voted to close with "Needs debugging details" and subsequently retracted, I cannot vote to close this question.
I'm new to the react.
I have this state :
state = {
isLoading: true,
};
And I have this lifecycle function
componentDidMount() {
const { setPageCount, receiveApiData } = this.props.actions;
const { isLoading } = this.state;
const getData = () => {
this.setState({ isLoading: !isLoading });
receiveApiData();
setPageCount();
};
setInterval(() => {
getData();
}, 30000);
}
Here is what I'm trying to return in render():
return isLoading ? (
<Loading></Loading>
) : ( `Some Code here`)
The problem is state is Always true and my lifecycle method is not changing it to the false so my app can not render the false condition.
I don't know what to do,any suggestions please?
Everything else in getData() is working correctly
The issue is here:
this.setState({ isLoading: !isLoading });
because isLoading what you are destructuring taking previous value i.e it is not taking latest state value so its not updating your isLoading . What you need to do is this:
this.setState({ isLoading: !this.state.isLoading });
Here is the demo: https://codesandbox.io/s/interesting-chandrasekhar-pluv7?file=/src/App.js:312-332
Since your new state depends on the value of your old state, you should use the functional form of setState
this.setState(prevState => ({
isLoading: !prevState.isLoading
}));
Official documentation: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
I want to set 'username' in the state to the localstorage.getItem,but the problem is it is not working,Any suggestions?
class ToDoApp extends Component {
state = {
username:'',
inputValue: '',
todos: [],
currentPage: 1,
pageCount: 1,
itemsPerPage: 10,
};
Function with posts item to the data:
addItem = () => {
let {todos} = this.state
let userName = localStorage.getItem('username')
console.log(userName)
if (this.inpRef.current.value === '') {
return alert('We dont do that here....')
} else {
axios
.post(`http://localhost:8080/add`, {
username:userName,
todo: this.inpRef.current.value,
checked: false,
})
.then((res) => {
this.setState({
todos:[...todos,{username:res.data.username,todo:res.data.todo,_id:res.data._id,checked:false}]
})
console.log(todos)
})
.catch((err) => {
console.log("err", err);
});
this.setPageCount()
}
this.inpRef.current.value = ''
console.log('--------this.state.todos', this.state.todos);
}
setState is async
can you try this:
this.setState({
todos:[...todos { username:res.data.username,todo:res.data.todo,_id:res.data._id,checked:false}]
}, console.log(this.state.todos))
setState has a callback as a second arg so you can check if it's actually been set here
constructor(props) {
super(props)
this.state = {
isEdit: false,
currentProduct : {
sku: '',
productName: '',
description: '',
duration: '',
},
}
}
handleChange = (e) => {
this.setState({
currentProduct: {
...this.state.currentProduct,
[e.target.name]: e.target.value
}
})
}
clickHandle = (e) => {
e.preventDefault()
const currentProduct = {...this.state.currentProduct}
currentProduct.id = this.props.match.params.id
this.props.updateProduct(currentProduct)
this.props.history.push('/')
}
When updating field it updates the values but when i goes again to update single value it update only that and removes the other don't know why
handleChange = (e) => {
this.setState({
...this.state.currentProduct,
[e.target.name]: e.target.value
})
}
you are not destructuring entire state first. so do ...state. otherwise isEdit field will be lost.
handleChange = e => {
this.setState({
...this.state,
currentProduct: {
...this.state.currentProduct,
[e.target.name]: e.target.value
}
});
};
I've read the docs here but I am having trouble getting the component to rerender after state is updated. The posts are being added, I just have to rerender the component manually to get them to show up, what am I missing?
I have this in the component:
class ListPosts extends Component {
state = {
open: false,
body: '',
id: ''
}
openPostModal = () => this.setState(() => ({
open: true,
}))
closePostModal = () => this.setState(() => ({
open: false,
}))
componentWillMount() {
const selectedCategory = this.props.selectedCategory;
this.props.fetchPosts(selectedCategory);
}
handleChange = (e, value) => {
e.preventDefault();
// console.log('handlechange!', e.target.value)
this.setState({ body: e.target.value });
};
submit = (e) => {
// e.preventDefault();
console.log(this.state.body)
const body = this.state.body;
const id = getUUID()
const category = this.props.selectedCategory;
const post = {
id,
body,
category
}
this.props.dispatch(addPost(post))
this.closePostModal()
}
Then down below I am adding the dispatch to props...
const mapStateToProps = state => ({
posts: state.postsReducer.posts,
loading: state.postsReducer.loading,
error: state.postsReducer.error,
selectedCategory: state.categoriesReducer.selectedCategory,
// selectedPost: state.postsReducer.selectedPost,
});
function mapDispatchToProps (dispatch) {
return {
fetchPosts: (selectedCategory) => dispatch(fetchPosts(selectedCategory)),
addPost: (postObj) => dispatch(addPost(postObj)),
}
}
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(ListPosts))
Here is the code for the reducer:
case C.ADD_POST :
const hasPost = state.some(post => post.id === action.payload.postObj.id)
console.log('caseADD_POST:', action.payload.postObj.id)
return (hasPost) ?
state :
[
...state,
post(null, action)
];