const NotePage = ({match, load_note,delete_note, update_note, create_note, note, isAuthenticated, history, user}) => {
const noteId = match.params.id
const [noteT, setNoteT] = useState({
body:'',
headline:'',
user_id: user
})
useEffect(() => {
getNote()
}, [noteId])
const getNote = async () => {
if (noteId === 'new') return
load_note(noteId)
setNoteT(note)
}
if (!isAuthenticated){
return <Redirect to='/login'/>
}
const handleChange = (e) => {
setNoteT(noteT => ({ ...noteT, [e.target.name]: e.target.value }))
}
const deleteNote = async () => {
delete_note(noteId)
history.push('/')
}
const handleSubmit = () => {
if (noteId !== 'new' && noteT.body === '') {
delete_note(noteId)
}else if(noteId !== 'new') {
console.log('update')
update_note(noteId, noteT)
}else if (noteId === 'new') {
setNoteT(noteT => ({...noteT, user_id: user}))
create_note(noteT)
}
history.push('/')
}
return(
<React.Fragment>
<div class = 'flex-none'>
<NoteNavBar/>
</div>
<div class='flex-1 py-2 grid justify-items-center'>
<textarea class='font-bold text-lg my-2 w-4/5 text-center text-gray-300 bg-gray-600' name='headline' onChange={(e) => { handleChange(e) }} value={noteT?.headline} ></textarea>
<textarea class='my-2 w-4/5 h-64 text-gray-300 bg-gray-600' name='body' onChange={(e) => { handleChange(e) }} value={noteT?.body}></textarea>
</div>
<div class=" flex justify-between">
<button onClick={deleteNote} class="font-bold border-2 rounded-md border-opacity-70 border-red-400 text-red-400 text-center px-2">Delete</button>
<button onClick={handleSubmit} >
<img src={Add} class='h-16' alt="fireSpot"/>
</button>
</div>
</React.Fragment>
);
};
const mapStateToProps = state => ({
note: state.notes.note,
isAuthenticated: state.auth.isAuthenticated,
user: state.auth.user.id,
});
export default connect(mapStateToProps, {create_note, load_note, delete_note, update_note})(NotePage);
Witam, szukam rozwiązania problemu. Obecny widok odpowiada za pokazanie w zależnosci od ID w linku który komponent ma pobrać z bazy i go wyświetlić. Problem w tym, że useEffect wywołuje się po wyrenderowaniu wszystkiego co za tym idzie noteT przypisywane jest z bazy po renderze i renderując ponownie z innym komponentem widoczny jest poprzedni. Funkcja w UseEffect zapisuje do stanu note potrzebny aktualnie komponent.
Czy ktoś wie jak mogę to rozwiązać ?. Działać działa :D tylko trzeba dwa razy wejść żeby się wyświetlił poprawny :D