This post contains the summary of what I learnt in fullstackopen (Part 2)
Higher Order Functions in Javascript such as map,filter,reduce and find:
Filter:
const ages = [32, 33, 16, 40];
const result = ages.filter(age=>{
return age>=18
})
Output:
[ 32, 33, 40 ]
Map:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(num=>{
return num*10
})
Output:
[ 650, 440, 120, 40 ]
Reduce:
const arr = [1.5, 20.3, 11.1, 40.7]
const total = arr.reduce((sum,item)=>{
return sum+item
},0)
Output:
73.6
Find:
const array = [10, 20, 30, 40, 50];
const found = array.find((element)=>{
return element > 20;
})
Output:
30
Key attribute
When rendering mapped out items, we need to assign the key
attribute to distinguish between each element.
useState hook
const [item,setItem] = useState(initialValue)
Note that the state updates asynchronously, so if you update an item using useState, it might not immediately be in effect until the next render.
Forms in React
<form onSubmit={addNote}>
<input
value={newNote}
onChange={handleNoteChange}
/>
<button type="submit">save</button> </form>
Using JSON server
After making a json file containing all the data.
Install json-server using
npm install json-server --save-dev
and then run
json-server --port 3000 --watch db.json
- Fetching data from server side We need to use axios to fetch data, therefore
npm install axios
To use axios
import axios from 'axios'
axios.get('http://localhost:3001/data')
.then(res=> console.log(res.data))
useEffect hook
It is used to fetch data from the server as it executes immediately upon render.
useEffect(() => {
axios
.get('http://localhost:3001/')
.then(response => {
setNotes(response.data)
})
}, [])
The array at the end is called the dependency array where you can pass variables and functions, which would cause the DOM to render upon changes in those variables and functions.
Axios post and put
POST
PUT:
axios.put(url, changedNote).then(response => {
setNotes(notes.map(note =>
note.id !== id ? note : response.data))
})
- Creating a separate module Keep all the axios requests in a separate module and maintain modularity and lastly export those functions using
export default {
getAll,
create,
update
}
Error Handling
Attaching
.catch(error){
console.log(error)
}
Outputs the error in case the request doesn't pass through
Top comments (0)