Add and Edit in same component in react - react-redux

if url is shipping/1245abcde, the form should load with the data comes from dispatch(getOrderDetails(orderId)). It does works fine when loading for first time but when I click refresh in the browser, it shows error at line: setAddress
TypeError: Cannot read property 'shippingAddress' of undefined
Here, I cannot call useSelector inside the useEffect. Is there anyway to get orderDetails state inside the useEffect().
Below is the ShippingScreen components
const ShippingScreen = ({ history, match }) => {
const orderId = match.params.orderId
const dispatch = useDispatch()
const cart = useSelector((state) => state.cart)
const { shippingAddress } = cart
const [address, setAddress] = useState(shippingAddress.address)
const [city, setCity] = useState(shippingAddress.city)
const [postalCode, setPostalCode] = useState(shippingAddress.postalCode)
const [country, setCountry] = useState(shippingAddress.country)
const orderDetails = useSelector((state) => state.orderDetails)
const { order } = orderDetails
useEffect(() => {
if (orderId) {
dispatch(getOrderDetails(orderId))
setAddress(order.shippingAddress.address)
setCity(order.shippingAddress.city)
setPostalCode(order.shippingAddress.postalCode)
setCountry(order.shippingAddress.country)
}
}, [orderId])

Related

useEffect => .then returns undefined

I try to fetch the current offer price for my NFT project but i currently get undefined in this function
useEffect(() => {
returnsCurrentOfferPrice(NFT.tokenId)
.then((offer) => {
console.log(offer);
setReturnCurrentOfferPrice(offer);
})
.catch((error) => {
console.log('Current offer price error', error);
});
}, [NFT.tokenId]);
This is my use State Snippet
const [returnCurrentOfferPrice, setReturnCurrentOfferPrice] = useState(null);
This is how i retrieve the function into my UI
const returnsCurrentOfferPrice = async (tokenId) => {
await getCurrentOfferPrice(tokenId)
}
And finally this is how i retrieve the data from the blockchain
const getCurrentOfferPrice = async (tokenId) => {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const contract = signerOrProvider(provider);
const currentOfferPrice = await contract.getCurrentOfferAmount(tokenId);
const bigNumber = ethers.BigNumber.from(currentOfferPrice);
const currentOfferPriceInEther = ethers.utils.formatEther(bigNumber)
console.log('Current offer price', currentOfferPriceInEther );
return currentOfferPriceInEther;
}

React - How can I improve my fetching like button data method

I often use this code to fetch and update data for my like button. It works but I wonder if there is a more effective or cleaner way to do this function.
const isPressed = useRef(false); // check the need to change the like count
const [like, setLike] = useState();
const [count, setCount] = useState(count_like); // already fetch data
const [haveFetch, setHaveFetch] = useState(false); // button block
useEffect(() => {
fetchIsLike(...).then((rs)=>{
setLike(rs);
setHaveFetch(true);
})
return () => {}
}, [])
useEffect(()=>{
if(like) {
// animation
if(isPressed.current) {
setCount(prev => (prev+1));
// add row to database
}
}
else {
// animation
if(isPressed.current) {
setCount(prev => (prev-1));
// delete row from database
}
}
}, [like])
const updateHeart = () => {
isPressed.current = true;
setLike(prev => !prev);
}

Dynamic axios request url in Vue 3 Composables

I've tried this and it worked:
const posts = ref{[]}
const urlEndPoint = 'posts'
const getPosts = async () => {
let response = await axios.get('/api/'+urlEndPoint)
posts.value = response.data.data
}
but that one is not dynamic. My goal is to make the urlEndPoint value reactive and set from the components
then i tried this:
const urlEndPoint = ref([])
but I don't know how to send the value of urlEndPoint constant back from the component to the composables.
I tried these in my component:
const urlEndPoint = 'posts'
and
const sendUrlEndPoint = () => {
urlEndPoint = 'posts'
}
but none worked.
is there a way to accomplish this goal? like sending the component name to urlEndPoint value in composable or any other simple way.
Define a composable function named use useFetch :
import {ref} from 'vue'
export default useFetch(){
const data=ref([])
const getData = async (urlEndPoint) => {
let response = await axios.get('/api/'+urlEndPoint)
data.value = response.data.data
}
return {
getData,data
}
in your component import the function and use it like :
const urlEndPoint=ref('posts')
const {getData:getPosts, data:posts}=useFetch()
getPosts(urlEndPoint.value)

selectfromresult rtk always undefined

// id comes from route and i use rtk query hook
but inquiry always be undefined and i log the data from useGetInquiriesQuery IT WORKS
WHAT IS THE BEST WAY TO DO
const { id } = useParams();
const validate = (input = values) => {
}
const [values, setValues, errors, setErrors, inputChanged] = useForm(initstate, validate)
const {inquiry} =useGetInquiriesQuery(undefined,{
selectFromResult:({data}) =>({
inquiry:data?.find((i)=> i.orderId === id),
}),
})
useEffect(()=>{
if(inquiry){
console.log(inquiry)
}
},[inquiry])

Selector for React-Redux

To use selector, I tried to follow this URL reference: https://blog.isquaredsoftware.com/2017/12/idiomatic-redux-using-reselect-selectors/
One of the example is :
const selectSomeData = state => state.someData;
const selectFilteredSortedTransformedData = createSelector(
selectSomeData,
(someData) => {
const filteredData = expensiveFiltering(someData);
const sortedData = expensiveSorting(filteredData);
const transformedData = expensiveTransformation(sortedData);
return transformedData;
}
)
const mapState = (state) => {
const transformedData = selectFilteredSortedTransformedData(state);
return {
data: transformedData
};
}
Question: Within mapState we are calling selectFilteredSortedTransformedData and we are also passing State as parameter. However, the function itself is not taking any parameter, how does it work?
const selectFilteredSortedTransformedData = createSelector(
did you add mapState function in redux connect function ?? something like this.
export default connect(mapState)(Component)

Resources