Im trying to make editing note functionality in my notes app and stuck on this point. Can somebody help me with it? In this version of code I have error 'dispatch is not a function' in EDIT_NOTE reducer.
So, here is my:
Actions:
import { ADD_NOTE, DELETE_NOTE, EDIT_NOTE } from './actionTypes'
export const editNoteAction = (text, id) => ({
type: EDIT_NOTE,
payload: {
id,
text,
},
})
Reducer:
import { nanoid } from 'nanoid'
import { ADD_NOTE, DELETE_NOTE, EDIT_NOTE } from './actionTypes'
const date = new Date()
export const initialState = {
notes: [
{
id: nanoid(),
text: '',
date: '',
},
],
}
export default function notes(state = initialState, { type, payload }) {
console.log(type)
switch (type) {
case ADD_NOTE: {
...
case DELETE_NOTE: {
...
case EDIT_NOTE: {
const editedNote = {
text: payload.text,
id: payload.id,
date: date.toLocaleDateString(),
}
return {
notes: state.notes.map((note) =>
note.id === payload.id
? {
...state,
notes: [...state.notes, editedNote],
}
: state
),
}
}
default:
return state
}
}
NoteList - the component where all notes are collected:
const NoteList = ({
Notes,
addNoteAction,
deleteNoteAction,
editNoteAction,
}) => {
console.log(Notes)
return (
<div className={styles.notesList}>
<AddNote handleAddNote={addNoteAction} />
{Notes.map((note) => (
<Note
key={note.id}
id={note.id}
text={note.text}
date={note.date}
handleDeleteNote={deleteNoteAction}
handleEditNote={editNoteAction}
/>
))}
</div>
)
}
const mapStateToProps = (state) => ({
Notes: state.notes || [],
})
const mapDispatchToProps = (dispatch) => ({
addNoteAction: (text) => dispatch(addNoteAction(text)),
deleteNoteAction: (id) => dispatch(deleteNoteAction(id)),
editNoteAction: (id) => dispatch(editNoteAction(id)),
})
export default connect(mapStateToProps, mapDispatchToProps)(NoteList)
And Note component
const Note = ({
id,
text,
date,
handleDeleteNote,
handleEditNote,
editNoteAction,
Notes,
}) => {
const [animType, setAnimType] = useState(AnimationTypes.ANIM_TYPE_ADD)
const [isEdit, setIsEdit] = useState(false)
const handleToggleEdit = () => {
if (!isEdit) {
editNoteAction(text)
}
setIsEdit(!isEdit)
}
const [newText, setNewText] = useState('')
const handleTextChange = (e) => {
setNewText(e.target.value)
}
const onNoteSave = () => {
handleToggleEdit()
editNoteAction({
id,
date,
text: newText,
})
}
return (
<div className={classnames(styles.note, styles[animType])}>
{isEdit ? (
<IsEditingNote
formalClassName={styles.editNote}
formalRef={noteTextareaRef}
formalOnChange={handleTextChange}
formalValue={newText}
/>
) : (
<span className={styles.noteText}>{text}</span>
)}
<div className={styles.noteFooter}>
<small>{date}</small>
<div className={styles.footerIcons}>
{!isEdit ? (
<EditingIcon
formalClassName={styles.editIcon}
formalOnClick={handleToggleEdit}
/>
) : (
<MdCheck
className={styles.deleteIcon}
size="1.4em"
onClick={onNoteSave}
/>
)}
<MdDeleteForever
className={styles.deleteIcon}
size="1.2em"
onClick={() => {
setAnimType(AnimationTypes.ANIM_TYPE_DELETE)
setTimeout(() => handleDeleteNote(id), 500)
}}
/>
</div>
</div>
</div>
)
}
const mapStateToProps = (state) => ({
Notes: state.notes || [],
})
const mapDispatchToProps = (dispatch) => ({
editNoteAction: (editedNote) => dispatch(editNoteAction(editedNote)),
})
export default connect(mapDispatchToProps, mapStateToProps)(Note)
Related
I have the following issue with website where the settings state resets after running more searches. The settings component is show below in the picture, it usually works but if you uncheck a box and then run a few more searches at some point the showAllDividends setting will be set to false, the All dividends component won't be on the screen, but for some reason the checkbox itself is checked (true). This is my first time really working with checkboxes in React, and I think I'm using the onChange feature wrong. Right now I get the event.target.checked boolean, but only onChange.
If that isn't the issue then the most likely cause is the default statements being run again on another render:
const [showMainInfo, setShowMainInfo] = useState(true);
const [showYieldChange, setShowYieldChange] = useState(true);
const [showAllDividends, setShowAllDividends] = useState(true);
the thing is I don't see why the default statements would run more than once, the component isn't being destroyed there's no react router usage. I expected it to keep its current state after the page is first loaded. I think the settings defaults are being rerun, but just don't understand why they would.
I unchecked, checked, unchecked the 'All dividends' checkbox, and it was unchecked when I ran 2 more searches. After the second search the checkbox was checked but the component was gone, because showAllDividends was false
main component SearchPage.js:
import React, {useState, useEffect} from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';
import SettingsView from './settings/SettingsView';
const HOST = process.env.REACT_APP_HOSTNAME
const PROTOCOL = process.env.REACT_APP_PROTOCOL
const PORT = process.env.REACT_APP_PORT
const BASE_URL = PROTOCOL + '://' + HOST + ':' + PORT
const SearchPage = ({userId}) => {
const DEFAULT_STOCK = 'ibm';
const [term, setTerm] = useState(DEFAULT_STOCK);
const [debouncedTerm, setDebouncedTerm] = useState(DEFAULT_STOCK);
const [loading, setLoading] = useState(false);
const [recentSearches, setRecentSearches] = useState([DEFAULT_STOCK]);
const [dividendsYearsBack, setDividendsYearsBack] = useState('3');
const [debouncedDividendYearsBack, setDebouncedDividendYearsBack] = useState('3');
const [errorMessage, setErrorMessage] = useState('');
const [dividendsData, setDividendsData] = useState(
{
current_price: '',
recent_dividend_rate: '',
current_yield: '',
dividend_change_1_year: '',
dividend_change_3_year: '',
dividend_change_5_year: '',
dividend_change_10_year: '',
all_dividends: [],
name: '',
description: '',
}
)
const [settingsViewVisible, setSettingsViewVisible] = useState(false);
const [showMainInfo, setShowMainInfo] = useState(true);
const [showYieldChange, setShowYieldChange] = useState(true);
const [showAllDividends, setShowAllDividends] = useState(true);
const onTermUpdate = (term) => {
setTerm(term)
}
// TODO: write a custom hook that debounces taking the term and the set debounced term callback
useEffect(() => {
const timerId = setTimeout(() => {
setDebouncedTerm(term);
}, 1500);
return () => {
clearTimeout(timerId);
};
}, [term]);
useEffect(() => {
const timerId = setTimeout(() => {
setDebouncedDividendYearsBack(dividendsYearsBack);
}, 1500);
return () => {
clearTimeout(timerId);
};
}, [dividendsYearsBack]);
useEffect(() => {runSearch()}, [debouncedTerm]);
useEffect(() => {
// alert(dividendsYearsBack)
if (dividendsYearsBack !== '') {
runSearch();
}
}, [debouncedDividendYearsBack])
useEffect(() => {
console.log("user id changed")
if (userId) {
const user_profile_api_url = BASE_URL + '/users/' + userId
axios.get(user_profile_api_url, {})
.then(response => {
const recent_searches_response = response.data.searches;
const new_recent_searches = [];
recent_searches_response.map(dict => {
new_recent_searches.push(dict.search_term)
})
setRecentSearches(new_recent_searches);
})
.catch((error) => {
console.log("error in getting user profile: ", error.message)
})
}
}, [userId])
useEffect(() => {
const user_profile_api_url = BASE_URL + '/users/' + userId
const request_data = {searches: recentSearches}
axios.post(user_profile_api_url, request_data)
// .then(response => {
// console.log(response)
// })
}, [recentSearches])
const makeSearchApiRequest = () => {
let dividends_api_url = BASE_URL + '/dividends/' + term + '/' + dividendsYearsBack
if (!recentSearches.includes(term)) {
setRecentSearches([...recentSearches, term])
}
axios.get(dividends_api_url, {})
.then(response => {
// console.log(response)
setLoading(false);
setDividendsData(response.data);
})
.catch((error) => {
console.log(error.message);
setLoading(false);
setErrorMessage(error.message);
})
}
const runSearch = () => {
console.log("running search: ", term);
setErrorMessage('');
if (term) {
setLoading(true);
if (!dividendsYearsBack) {
setDividendsYearsBack('3', () => {
makeSearchApiRequest()
});
} else {
makeSearchApiRequest()
}
}
}
const recentSearchOnClick = (term) => {
setTerm(term);
setDebouncedTerm(term);
}
const removeRecentSearchOnClick = (term) => {
const searchesWithoutThisOne = recentSearches.filter(search => search !== term)
setRecentSearches(searchesWithoutThisOne);
}
const dividendsYearsBackOnChange = (text) => {
setDividendsYearsBack(text);
}
const renderMainContent = () => {
if (!debouncedTerm) {
return (
<div className="ui active">
<div className="ui text">Search for info about a stock</div>
</div>
)
}
if (loading === true) {
return (
<div className="ui active dimmer">
<div className="ui big text loader">Loading</div>
</div>
)
}
if (errorMessage) {
return (
<div className="ui active">
<div className="ui text">{errorMessage}</div>
</div>
)
} else {
return (
<DividendResultsDisplay
data={dividendsData}
dividends_years_back={dividendsYearsBack}
dividendsYearsBackOnChange={dividendsYearsBackOnChange}
showMainInfo={showMainInfo}
showYieldChange={showYieldChange}
showAllDividends={showAllDividends}/>
)
}
}
// https://stackoverflow.com/questions/38619981/how-can-i-prevent-event-bubbling-in-nested-react-components-on-click
const renderRecentSearches = () => {
return recentSearches.map((term) => {
return (
<div key={term}>
<button
onClick={() => recentSearchOnClick(term)}
style={{marginRight: '10px'}}
>
<div>{term} </div>
</button>
<button
onClick={(event) => {event.stopPropagation(); removeRecentSearchOnClick(term)}}>
X
</button>
<br/><br/>
</div>
)
})
}
const renderSettingsView = (data) => {
if (settingsViewVisible) {
return (
<SettingsView data={data} />
)
} else {
return null;
}
}
const toggleSettingsView = () => {
setSettingsViewVisible(!settingsViewVisible);
}
const toggleDisplay = (e, setter) => {
setter(e.target.checked)
}
const SETTINGS_DATA = [
{
label: 'Main info',
id: 'main_info',
toggler: toggleDisplay,
setter: setShowMainInfo
},
{
label: 'Yield change',
id: 'yield_change',
toggler: toggleDisplay,
setter: setShowYieldChange
},
{
label: 'Dividends list',
id: 'all_dividends',
toggler: toggleDisplay,
setter: setShowAllDividends
},
]
console.log("showMainInfo: ", showMainInfo);
console.log("showYieldChange: ", showYieldChange);
console.log("showAllDividends: ", showAllDividends);
return (
<div className="ui container" style={{marginTop: '10px'}}>
<SearchBar term={term} onTermUpdate={onTermUpdate} />
{renderRecentSearches()}
<br/><br/>
<button onClick={toggleSettingsView}>Display settings</button>
{renderSettingsView(SETTINGS_DATA)}
<div className="ui segment">
{renderMainContent()}
</div>
</div>
)
}
const mapStateToProps = state => {
return { userId: state.auth.userId };
};
export default connect(
mapStateToProps
)(SearchPage);
// export default SearchPage;
the settingsView component:
import React from 'react';
import SettingsCheckbox from './SettingsCheckbox';
const SettingsView = ({data}) => {
const checkboxes = data.map((checkbox_info) => {
return (
<div key={checkbox_info.id}>
<SettingsCheckbox
id={checkbox_info.id}
label={checkbox_info.label}
toggler={checkbox_info.toggler}
setter={checkbox_info.setter}/>
<br/>
</div>
)
});
return (
<div className="ui segment">
{checkboxes}
</div>
);
}
export default SettingsView;
SettingsCheckbox.js:
import React, {useState} from 'react';
const SettingsCheckbox = ({id, label, toggler, setter}) => {
const [checked, setChecked] = useState(true)
return (
<div style={{width: '200px'}}>
<input
type="checkbox"
checked={checked}
id={id}
name={id}
value={id}
onChange={(e) => {
setChecked(!checked);
toggler(e, setter);
}} />
<label htmlFor="main_info">{label}</label><br/>
</div>
);
}
export default SettingsCheckbox;
I'm working on a React Notes Application and my App.js contains all the necessary functions props which are passed down to several components.
As a result I'm doing prop drilling a lot where I'm passing down around 10-20 props/functions in the components where it isn't needed.
I tried using useContext Hook but I guess it doesn't work with callback functions in the value parameter.
App.js
const App = () => {
const [ notes, setNotes ] = useState([]);
const [ category, setCategory ] = useState(['Notes']);
const [ searchText, setSearchText ] = useState('');
const [ alert, setAlert ] = useState({
show:false,
msg:'',
type:''
});
const [isEditing, setIsEditing] = useState(false);
const [editId, setEditId] = useState(null);
useEffect(()=>{
keepTheme();
})
// retreive saved notes
useEffect(()=>{
const savedNotes = JSON.parse(localStorage.getItem('react-notes-data'));
if (savedNotes) {
setNotes(savedNotes)
}
}, []);
// save notes to local storage
useEffect(() => {
localStorage.setItem('react-notes-data', JSON.stringify(notes))
setNotesCopy([...notes]);
}, [notes]);
// save button will add new note
const addNote = (text) => {
const date = new Date();
const newNote = {
id: nanoid(),
text: text,
date: date.toLocaleDateString(),
category: category,
}
const newNotes = [...notes, newNote]
setNotes(newNotes);
}
const deleteNote = (id) => {
showAlert(true, 'Note deleted', 'warning');
const newNotes = notes.filter(note => note.id !== id);
setNotes(newNotes);
}
// hardcoded values for categories
const allCategories = ['Notes', 'Misc', 'Todo', 'Lecture Notes', 'Recipe'];
// copy notes for filtering through
const [notesCopy, setNotesCopy] = useState([...notes]);
const handleSidebar = (category) => {
setNotesCopy(category==='Notes'?[...notes]:
notes.filter(note=>note.category===category));
}
// function to call alert
const showAlert = (show=false, msg='', type='') => {
setAlert({show, msg, type});
}
return (
<div>
<div className="container">
<Sidebar
allCategories={allCategories}
handleSidebar={handleSidebar}
notesCopy={notesCopy}
key={notes.id}
/>
<Header notes={notes} alert={alert} removeAlert={showAlert} />
<Search handleSearchNote={setSearchText} />
<NotesList
notesCopy={notesCopy.filter(note=>
note.text.toLowerCase().includes(searchText) ||
note.category.toString().toLowerCase().includes(searchText)
)}
handleAddNote={addNote}
deleteNote={deleteNote}
category={category}
setCategory={setCategory}
allCategories={allCategories}
showAlert={showAlert}
notes={notes}
setNotes={setNotes}
editId={editId}
setEditId={setEditId}
isEditing={isEditing}
setIsEditing={setIsEditing}
/>
</div>
</div>
)
}
NotesList.js
const NotesList = (
{ notesCopy, handleAddNote, deleteNote, category, setCategory, showHideClassName, allCategories, showAlert, isEditing, setIsEditing, notes, setNotes, editId, setEditId }
) => {
const [ noteText, setNoteText ] = useState('');
const textareaRef = useRef();
// function to set edit notes
const editItem = (id) => {
const specificItem = notes.find(note=>note.id === id);
setNoteText(specificItem.text);
setIsEditing(true);
setEditId(id);
textareaRef.current.focus();
}
return (
<div key={allCategories} className="notes-list">
{notesCopy.map(note => {
return (
<Note
key={note.id}
{...note}
deleteNote={deleteNote}
category={note.category}
isEditing={isEditing}
editId={editId}
editItem={editItem}
/>)
})}
<AddNote
handleAddNote={handleAddNote}
category={category}
setCategory={setCategory}
showHideClassName={showHideClassName}
allCategories={allCategories}
showAlert={showAlert}
isEditing={isEditing}
setIsEditing={setIsEditing}
notes={notes}
setNotes={setNotes}
editId={editId}
setEditId={setEditId}
noteText={noteText}
setNoteText={setNoteText}
textareaRef={textareaRef}
/>
</div>
)
}
AddNote.js
const AddNote = ({ notes, setNotes, handleAddNote, category, setCategory, showHideClassName, allCategories, showAlert, isEditing, setIsEditing, editId, setEditId, noteText, setNoteText, textareaRef }) => {
const [ show, setShow ] = useState(false);
const [ modalText, setModalText ] = useState('');
const charCount = 200;
const handleChange = (event) => {
if (charCount - event.target.value.length >= 0) {
setNoteText(event.target.value);
}
}
const handleSaveClick = () => {
if (noteText.trim().length === 0) {
setModalText('Text cannot be blank!');
setShow(true);
}
if (category === '') {
setModalText('Please select a label');
setShow(true);
}
if (noteText.trim().length > 0 && category!=='') {
showAlert(true, 'Note added', 'success');
handleAddNote(noteText);
setNoteText('');
setShow(false);
}
if (noteText.trim().length > 0 && category!=='' && isEditing) {
setNotes(notes.map(note=>{
if (note.id === editId) {
return ({...note, text:noteText, category:category})
}
return note
}));
setEditId(null);
setIsEditing(false);
showAlert(true, 'Note Changed', 'success');
}
}
const handleCategory = ( event ) => {
let { value } = event.target;
setCategory(value);
}
showHideClassName = show ? "modal display-block" : "modal display-none";
return (
<div className="note new">
<textarea
cols="10"
rows="8"
className='placeholder-dark'
placeholder="Type to add a note.."
onChange={handleChange}
value={noteText}
autoFocus
ref={textareaRef}
>
</textarea>
<div className="note-footer">
<small
className='remaining'
style={{color:(charCount - noteText.length == 0) && '#c60000'}}>
{charCount - noteText.length} remaining</small>
<div className='select'>
<select
name={category}
className="select"
onChange={(e)=>handleCategory(e)}
required
title='Select a label for your note'
defaultValue="Notes"
>
<option value="Notes" disabled selected>Categories</option>
{allCategories.map(item => {
return <option key={item} value={item}>{item}</option>
})}
</select>
</div>
<button className='save' onClick={handleSaveClick} title='Save note'>
<h4>{isEditing ? 'Edit':'Save'}</h4>
</button>
</div>
{/* Modal */}
<main>
<div className={showHideClassName}>
<section className="modal-main">
<p className='modal-text'>{modalText}</p>
<button type="button" className='modal-close-btn'
onClick={()=>setShow(false)}><p>Close</p>
</button>
</section>
</div>
</main>
</div>
)
}
I want the functions passed from App.js to NotesList.js to be in AddNote.js without them being passed in NotesList.js basically minimizing the props destructuring in NotesList.js
Context API does work with function. What you need to do is pass your function to Provider inside value :
<MyContext.Provider value={{notes: notesData, handler: myFunction}} >
For example:
// notes-context.js
import React, { useContext, createContext } from 'react';
const Context = createContext({});
export const NotesProvider = ({children}) => {
const [notes, setNote] = useState([]);
const addNote = setNote(...); // your logic
const removeNote = setNote(...); // your logic
return (
<Context.Provider value={{notes, addNote, removeNote}}>
{children}
</Context.Provider>
)
}
export const useNotes = () => useContext(Context);
Add Provider to your App.js like so:
// App.js
import NoteProvider from './notes-context';
export default App = () => {
return (
<NoteProvider>
<div>... Your App</div>
</NoteProvider>
)
}
Then call UseNote in your NoteList.js to use the function:
// NoteList.js
import {useNotes} from './note-context.js';
export const NoteList = () => {
const {notes, addNotes, removeNotes} = useNotes();
// do your stuff. You can now use functions addNotes and removeNotes without passing them down the props
}
After receiving data from the API then mapping it out - I tried toggling one icon, but it toggles all the icons that were mapped out. I am trying to click one of the icon and not all.
import { FaRegHeart, FaHeart } from "react-icons/fa";
import { IconContext } from 'react-icons';
import { useState, useEffect } from 'react';
const Replies = ({ comments, id }) => {
const [liked, setLiked] = useState(false);
const [replies, setReplies] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch('http://192.168.1.98:5000/blogs/' + id, { signal: abortCont.signal })
.then(res => {
if (!res.ok) {
throw new Error('Could not get data from the database');
}
return res.json()
})
.then(data => setReplies(data))
.catch(err => {
if (err.name === 'AbortError') {
// empty if statement
}})
return () => abortCont.abort()
}, [liked])
const likeComment = () => {liked ? setLiked(false) : setLiked(true)}
return (
<>
{replies && <div className="commentSection">
{
replies.discussion.map((discussion) => (
<div key={discussion.id}>
<div className="commentEmoji">
{
liked ? <IconContext.Provider value={{ color: 'red', className: 'love-icon' }}>
<FaHeart onClick={likeComment} />
</IconContext.Provider>
: <FaRegHeart onClick={likeComment} />}
</div>
</div>
))}
</div>
}
</>
);
}
export default Replies;
This is what the API looks like:
"discussion": [
{
"id": 1,
"liked": false,
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg",
"user": "Kayode",
"comment": "They know electric vehicles are the future 👌🏾",
"replies": ""
},
{
"user": "Farook",
"liked": true,
"id": 2,
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/74.jpg",
"comment": "I hope they keep buying. TSLA to that freaking moon 🚀",
"replies": ""
}
]
They have a discussion.liked property and I've been trying to access individual and not both.
If I use:
<FaRegHeart onClick={()=> likeComment(discussion.id)} />
Then
const likeComment = (id) => {
console.log(id) //it logs the exact id of the icon i.e 2
}
Try something like this, and pass appropriate props in LikedButton component
import { FaRegHeart, FaHeart } from "react-icons/fa";
import { IconContext } from 'react-icons';
import { useState, useEffect } from 'react';
const LikedButton = () => {
const [liked, setLiked] = useState(false);
const likeComment = () => {liked ? setLiked(false) : setLiked(true)}
return (
<div >
<div className="commentEmoji">
{
liked ? <IconContext.Provider value={{ color: 'red', className: 'love-icon' }}>
<FaHeart onClick={likeComment} />
</IconContext.Provider>
: <FaRegHeart onClick={likeComment} />}
</div>
</div>
)
}
const Replies = ({ comments, id }) => {
const [replies, setReplies] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch('http://192.168.1.98:5000/blogs/' + id, { signal: abortCont.signal })
.then(res => {
if (!res.ok) {
throw new Error('Could not get data from the database');
}
return res.json()
})
.then(data => setReplies(data))
.catch(err => {
if (err.name === 'AbortError') {
// empty if statement
}})
return () => abortCont.abort()
}, [])
return (
<>
{replies && <div className="commentSection">
{
replies.discussion.map((discussion, index) => (
<LikedButton key={index} />
))}
</div>
}
</>
);
}
export default Replies;
import LikedComment from './LikedComment';
import { useState, useEffect } from 'react';
const Replies = ({ comments, id }) => {
const [error, setError] = useState(false);
const [replies, setReplies] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch('http://192.168.1.98:5000/blogs/' + id, { signal: abortCont.signal })
.then((res) => {
if (!res.ok) {
throw new Error('Could not get data from the database');
}
return res.json();
})
.then((data) => {
setReplies(data);
})
.catch((err) => {
if (err.name === 'AbortError') {
// empty if statement
} else {
setError(true);
}
});
return () => abortCont.abort();
}, [id]);
const likeComment = (id) => {
setReplies({
...replies,
discussion: replies.discussion.map((reply) => {
if (reply.id === id) {
return { ...reply, liked: !reply.liked };
} else {
return reply;
}
}),
});
};
return (
<>
{error && <div className="commentError">Cannot retrieve comments </div>}
{replies && (
<div className="commentSection">
{replies.discussion.map((discussion, index) => (
<div key={discussion.id}>
<div className="comment">
<img className="commentImg" src={discussion.thumbnail} alt="" />
<div className="commentBody">
<p>
{' '}
<span>{discussion.user}</span> {discussion.comment}
</p>
</div>
<div className="commentEmoji">
<LikedComment
liked={discussion.liked}
key={index}
likeComment={() => likeComment(discussion.id)}
/>
</div>
</div>
</div>
))}
</div>
)}
</>
);
};
export default Replies;
I am building a to-do/notes app in order to learn the basics of Redux, using React hooks and Typescript.
A note is composed of an ID and a value. The user can add, delete or edit a note.
The add / delete mechanics work fine. But the edit one is trickier for me, as I'm questionning how it should be implemented.
I think my reducer's code is fine. The problem lies between my component (Note.tsx) and its parent one (App.tsx).
When i'm logging the value, I can see that the new updated/edited value of the note is not sent to the reducer. As a result, my note is not edited with the new value.
I've tried "cloning" the redux store and making my changes here, but it seems tedious and unnatural to me. Should I just call the edit method from my Note.tsx component ?
Is there a clean / conventional way to do this ?
Here is my code :
App.tsx
function App() {
const notes = useSelector<NotesStates, NotesStates['notes']>(((state) => state.notes));
const dispatch = useDispatch();
const onAddNote = (note: string) => {
dispatch(addNote(note));
};
const onDeleteNote = (note: NoteType) => {
dispatch(deleteNote(note));
};
const onEditNote = (note: NoteType) => {
dispatch(updateNote(note));
};
return (
<div className="home">
<NewNoteInput addNote={onAddNote} />
<hr />
<ul className="notes">
{notes.map((note) => (
<Note
updateNote={() => onEditNote(note)}
deleteNote={() => onDeleteNote(note)}
note={note}
/>
))}
</ul>
</div>
);
}
Note.tsx
interface NoteProps {
deleteNote(): void
updateNote(noteValue: string | number): void
note: NoteType
}
const Note: React.FC<NoteProps> = ({ deleteNote, updateNote, note: { id, value } }) => {
const [isEditing, setIsEditing] = useState(false);
const [newNoteValue, setNewNoteValue] = useState(value);
const onDeleteNote = () => {
deleteNote();
};
const onUpdateNote = () => {
updateNote(newNoteValue);
setIsEditing(false);
};
const handleOnDoubleClick = () => {
setIsEditing(true);
};
const renderBody = () => {
if (!isEditing) {
return (
<>
{!value && <span className="empty-text">Note is empty</span>}
<span>{value}</span>
</>
);
}
return (
<input
value={newNoteValue}
onChange={(e) => setNewNoteValue(e.target.value)}
onBlur={onUpdateNote}
/>
);
};
return (
<li className="note" key={id}>
<span className="note__title">
Note n°
{id}
</span>
<div className="note__body" onDoubleClick={handleOnDoubleClick}>
{renderBody()}
</div>
<button type="button" onClick={onDeleteNote}>Delete</button>
</li>
);
};
export default Note;
and the notesReducer.tsx
export interface NotesStates {
notes: Note[]
}
export interface Note {
id: number
value: string
}
const initialState = {
notes: [],
};
let noteID = 0;
export const notesReducer = (state: NotesStates = initialState, action: NoteAction): NotesStates => {
switch (action.type) {
case 'ADD_NOTE': {
noteID += 1;
return {
...state,
notes: [...state.notes, {
id: noteID,
value: action.payload,
}],
};
}
case 'UPDATE_NOTE': {
return {
...state,
notes: state.notes.map((note) => {
if (note.id === action.payload.id) {
return {
...note,
value: action.payload.value,
};
}
return note;
}),
};
}
case 'DELETE_NOTE': {
return {
...state,
notes: [...state.notes
.filter((note) => note.id !== action.payload.id)],
};
}
default:
return state;
}
};
Thanks to #secan in the comments I made this work, plus some changes.
In App.tsx :
<Note
updateNote={onEditNote}
deleteNote={() => onDeleteNote(note)}
note={note}
/>
In Note.tsx :
interface NoteProps {
deleteNote(): void
updateNote(newNote: NoteType): void // updated the signature
note: NoteType
}
// Now passing entire object instead of just the value
const onUpdateNote = (newNote: NoteType) => {
updateNote(newNote);
setIsEditing(false);
};
const renderBody = () => {
if (!isEditing) {
return (
<>
{!value && <span className="empty-text">Note is empty</span>}
<span>{value}</span>
</>
);
}
return (
<input
value={newNoteValue}
onChange={(e) => setNewNoteValue(e.target.value)}
// modifying current note with updated value
onBlur={() => onUpdateNote({ id, value: newNoteValue })}
/>
);
};
Guys I need help to make an API search request that should be done when page is ready.
This is state object:
const [state, setState] = useState({
s: "",
results: [],
selected: {}
});
const apiurl = ....;
This is how my search input actually works:
const search = (e) => {
if (e.key === "Enter") {
axios(apiurl + "&s=" + state.s).then(({data}) => {
let results = data.Search;
setState(prevState => {
return {...prevState, results: results }
});
});
}
}
const handleInput = (e) => {
let s = e.target.value;
setState(prevState => {
return { ...prevState, s: s }
});
}
My components:
return (
<div className='basic'>
<Header />
<Search handleInput={handleInput} search={search} />
<Container>
<Results results={state.results} openPopup={openPopup} />
{(typeof state.selected.Title != "undefined") ? <Popup selected={state.selected} closePopup={closePopup} /> : false }
</Container>
</div>
);
Search.js:
function Search ({ handleInput, search})
return (
<Container bg="dark" variant="dark">
<section className="searchbox-wrap">
<input
type="text"
placeholder="Поиск фильма"
className="searchbox"
onChange={handleInput}
onKeyPress={search}
/>
</section>
</Container>
)
Results.js:
function Results ({ results, openPopup }) {
return (
<section className="results">
{results.map(result => (
<Result key={result.imdbID} result={result} openPopup={openPopup} />
))}
</section>
);
}
So how can I make search request (for example: Superman) be done when page is loaded? Thank you!
You can do that with useEffect hook, that is equivalent to componentDidMount() lifecycle method when an empty array is passed as a second argument. So modified code would look like the following:
import React, { useState, useEffect, useCallback } from 'react';
function SearchComponent() {
const [state, setState] = useState({
s: "Superman",
results: [],
selected: {}
});
const apiurl = "";
const makeSearchRequest = useCallback(
searchString => {
axios(apiurl + "&s=" + searchString)
.then(({ data }) => data.Search)
.then(results => setState(prevState => ({ ...prevState, results })));
},
[setState]
);
// This will be invoked only on component mount
useEffect(() => makeSearchRequest(state.s), []);
const handleInput = useCallback(
e => {
e.persist();
setState(prevState => ({ ...prevState, s: e.target.value }));
},
[setState]
);
const search = useCallback(
e => {
if (e.key === "Enter") {
makeSearchRequest(state.s);
}
},
[makeSearchRequest, state.s]
);
return (
<input
type="text"
value={state.s}
onChange={handleInput}
onKeyPress={search}
/>
);
}