TypeError: failed to fetch mern - typeerror

I'm on Course "React, NodeJS, Express & MongoDB - The MERN Fullstack Guide" Section "Connecting the React.js Frontend to the Backend". Can anyone guide me on why I'm getting this error? Whenever I Update or delete a place it shows the error: TypeError: Failed to fetch What can I do about that?
const UserPlaces = () => {
const [loadedPlaces, setLoadedPlaces] = useState();
const { isLoading, error, sendRequest, clearError } = useHttpClient();
const userId = useParams().userId;
useEffect(() => {
const fetchPlaces = async () => {
try {
const responseData = await sendRequest(
`http://localhost:5000/api/places/user/${userId}`
);
setLoadedPlaces(responseData.places);
} catch (err) { }
};
fetchPlaces();
}, [sendRequest, userId]);
const placeDeletedHandler = deletedPlaceId => {
setLoadedPlaces(prevPlaces =>
prevPlaces.filter(place => place.id !== deletedPlaceId)
);
};
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && (
<div className="center">
<LoadingSpinner />
</div>
)}
{!isLoading && loadedPlaces && <PlaceList items={loadedPlaces} onDeletePlace={placeDeletedHandler} />}
</React.Fragment>
);
};
export default UserPlaces;
Frontend: https://github.com/sharjeelyunus/peek-mern
Backend: https://github.com/sharjeelyunus/peek-mern-api

Found the answer: that was the cores error. you just have to add cors.
var cors = require('cors');
app.use(cors(), (req, res, next) = {}

Related

React Native with API, Error: undefined is not an object

I'M trying to use Weather API with React Native, but the error below occurred.
It seems that a problem is that const is used before getAdressData done.
How can I use const in this case and fix this error?
Error
undefined is not an object (evaluating 'whether.sys.sunrise')
Codes
〜〜〜〜〜〜〜〜〜〜
export const AddressScreen = () => {
const [address, setAddress] = useState('');
const baseURL = `${APIKey}`
const getAddressData = () => {
axios.get(baseURL)
.then((response) => {setAddress(response.data)})
.catch(error => console.log(error))
};
const sunrise = new Date(weather.sys.sunrise * 1000); //Error
const sunriseTime = sunrise.toLocaleTimeString();
return (
<KeyboardAvoidingView>
〜〜〜〜〜〜〜〜
<View>
<Text>
Sunrise: {(sunriseTime)}
</Text>
</View>
</KeyboardAvoidingView>
);
The JavaScript compiler error is clear with the error. you are trying to access weather.sys.sunrise object property but not defined/initialized.
It seems that you are trying to fetch weather information of a specific location. If that is the intention of your code.
Refactor code as below :
export const AddressScreen = () => {
const [address, setAddress] = useState(null);
const baseURL = `${APIKey}`;
console.log("Fetched weather data:",address)
const getAddressData = () => {
axios
.get(baseURL)
.then((response) => {
console.log("Server response:",response)
setAddress(response.data);
})
.catch((error) => console.log(error));
};
useEffect(() => {
getAddressData();
}, []);
// Don't access weather data until fetched and assigned to state value.
if (!address?.sys) return null;
const sunrise = new Date(address.sys.sunrise * 1000);
const sunriseTime = sunrise.toLocaleTimeString();
return (
<KeyboardAvoidingView>
<View>
<Text>Sunrise: {sunriseTime}</Text>
</View>
</KeyboardAvoidingView>
);
};

Promise Rejection with axios. try to make HTTP instead of HTTPs [ duplicate ]

I pull data from the API and write it to the application with usestate() when the app runs there are no problems, but after 10-30 seconds I get this error.
Here is my code.
const App = () => {
const [datas, setDatas] = useState([])
const res = async () => {
const response = await axios.get("http://hasanadiguzel.com.tr/api/kurgetir")
setDatas(response.data.TCMB_AnlikKurBilgileri)
}
res()
return (
<SafeAreaView style={style.container}>
<View>
{datas.map((item) => {
return (
<KurCard
title={item.Isim}
alis={item.BanknoteBuying}
satis={item.BanknoteSelling}
/>
)
})}
</View>
</SafeAreaView>
)
}
How can I fix this ?
Hi #n00b,
The problem is with your URL Protocol.
const App = () => {
const [datas, setDatas] = useState([]);
const res = async () => {
try {
const url = "https://hasanadiguzel.com.tr/api/kurgetir";
const response = await axios.get(url);
const data = await response.data;
console.log(data.TCMB_AnlikKurBilgileri); // check you console.
setDatas(response.data.TCMB_AnlikKurBilgileri);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
res();
}, []);
And also check this out:- Codesandbox.
And please read this Stack Overflow discussion for better understanding:- stackoverflow

making several api calls slows down react native app

So I am calling getUserProducts() (to show the updated list) whenever a product is added to the list and whenever a product is deleted from the list. But I've noticed when I add several items to the list through the dropdown, some times the product doesn't show in the list/getUserProducts isn't called (and then if I add another product it'll then show the previous added product) I'm assuming its because I'm calling it every time I add and that's making it slow? Is there a way I can work around this to optimize it?
const App = () => {
const [products, setProducts] = useState<ProductType[] | []>([]);
const [userProducts, setUserProducts] = useState<ProductType[] | []>([]);
const [toggleCheckBox, setToggleCheckBox] = useState(false);
const [value, setValue] = useState(' ');
const [isFocus, setIsFocus] = useState(false);
const [visible, setVisible] = useState(false);
const [productId, setProductId] = useState('');
const [product, setProduct] = useState('');
const [num, setNum] = useState('');
const [amount, setAmount] = useState('');
const submitForm = async () => {
let body;
body = {
product_id: productId,
product: product,
num: num,
amount: amount,
};
const response = await postProduct(body);
if (response == undefined) {
return;
}
};
const getProducts = async () => {
try {
const response = await axios.get('http://192.168.1.32:3000/api/products');
setProducts(response.data);
} catch (error) {
// handle error
alert('no');
}
};
const getUserProducts = async () => {
try {
const response = await axios.get(
'http://192.168.1.32:3000/api/user_products',
);
setUserProducts(response.data);
} catch (error) {
// handle error
alert('no');
}
};
React.useEffect(() => {
getProducts();
getUserProducts();
console.log(userProducts);
}, []);
return (
<>
<Provider>
<Dialog visible={visible} onDismiss={() => setVisible(false)}>
<DialogHeader title="Add to your list" />
<DialogContent>
<Dropdown
style={[styles.dropdown, isFocus && {borderColor: 'blue'}]}
data={products}
search
maxHeight={300}
labelField="product"
valueField="num"
placeholder={!isFocus ? 'Select item' : '...'}
searchPlaceholder="Search..."
value={value}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setValue(item.num);
setProductId(item.product_id);
setProduct(item.product);
setNum(item.num);
setIsFocus(false);
}}
/>
<TextInput
label="quantity"
variant="standard"
onChangeText={text => {
setAmount(text);
console.log(text);
}}
/>
</DialogContent>
<DialogActions>
<Button
title="Cancel"
compact
variant="text"
onPress={() => setVisible(false)}
/>
<Button
title="Add"
compact
variant="text"
onPress={() => {
setVisible(false);
submitForm();
console.log('added');
getUserProducts();
}}
/>
</DialogActions>
</Dialog>
{userProducts.length > 0 ? (
userProducts.map(userProduct => (
<ListItem
title={
userProduct.product +
' x' +
userProduct.amount +
' num: ' +
userProduct.num
}
onPress={async () => {
await deleteProduct(userProduct.product_id);
console.log('deleted');
getUserProducts();
ToastAndroid.show('Done', ToastAndroid.SHORT);
}}
trailing={
<CheckBox
disabled={false}
value={toggleCheckBox}
onValueChange={newValue => setToggleCheckBox(newValue)}
/>
}
/>
))
) : (
<Text>Nothing in your list yet</Text>
)}
</Provider>
</>
);
};
export default App;
I'm pretty certain that you aren't experiencing "lag" but race conditions.
See, when you create an item, you call submitForm() and getuserProducts() and both are async functions. Depending on how long the individual requests take, or how their execution gets scheduled getuserProducts() may very well finish before submitForm(). The new data then only reaches the server after you fetched the (not so) new data.
Consider the following code (it's just a simplified version of your app):
import React, { useState } from 'react';
interface ProductType {
id: number;
name: string;
}
export default function NotWorking() {
const [products, setProducts] = useState<ProductType[]>([]);
const createProduct = async () => {
await serverCreateProduct(`product: ${products.length}`);
console.log('product created');
};
const getProducts = async () => {
setProducts(await serverGetProducts());
console.log('products loaded...');
};
return (
<div>
<button
onClick={() => {
createProduct();
getProducts();
}}
>
Add
</button>
<h2>List:</h2>
<ul>
{products.map((product) => (
<li key={String(product.id)}>{product.name}</li>
))}
</ul>
</div>
);
}
const _userProducts: ProductType[] = [];
async function serverGetProducts() {
return new Promise<ProductType[]>((resolve) => {
setTimeout(() => {
resolve([..._userProducts]);
}, 300);
});
}
async function serverCreateProduct(name: string) {
return new Promise<void>((resolve) => {
setTimeout(() => {
_userProducts.push({ id: Math.random(), name });
resolve();
}, 500);
});
}
If you execute it, you will see that getProducts() finishes before createProduct(), so that result cannot include the new data.
You should await both of them, in order to get what you want, for example:
const createProduct = async () => {
await serverCreateProduct(`product: ${products.length}`);
console.log('product created');
setProducts(await serverGetProducts());
console.log('products loaded');
};
// ...
<button onClick={() => createProduct()}>Add</button>
See the code working here.

can't retrieve key from async storage react native

I am trying to store the user email with async storage using a remember me toggle switch. I am not sure why I am retrieving "null" with my getRememberedUser call? What am I doing wrong? This is React Native , and I also have a redux store (not really using here), but not sure if that is important. Thanks!
const [userEmail, setuserEmail] = useState("");
const [rememberMe, setrememberMe] = useState(false);
const rememberUser = async () => {
try {
await AsyncStorage.setItem("userEmail", userEmail);
console.log("stored");
} catch (error) {
// Error saving data
}
};
const forgetUser = async () => {
try {
await AsyncStorage.removeItem("userEmail");
console.log("forgotten");
} catch (error) {
// Error removing
}
};
const getRememberedUser = async () => {
try {
const value = await AsyncStorage.getItem("userEmail");
console.log(value)
if (value !== null) {
// We have username!!
setuserEmail(value);
}
} catch (error) {
// Error retrieving data
}
};
<Input
id="email"
label="E-Mail"
keyboardType="email-address"
required
email
autoCapitalize="none"
errorText="Please enter a valid email address."
onInputChange={inputChangeHandler}
initialValue={userEmail}
/>
<Switch
value={rememberMe}
onValueChange={(value) => toggleRememberMe(value)}
/>
<Text>Remember Me</Text>
<Button
title="get uersname"
onPress={() => {
getRememberedUser();
}}
></Button>
You need to stringify when saving,
await AsyncStorage.setItem("userEmail", JSON.stringify(userEmail));
and parse when retrieving
const value = await AsyncStorage.getItem("userEmail");
const userEmail = JSON.parse(value);

React Native User Login Problem ( AsyncStorage )

I am trying to make a membership login system but I get an error. I couldn't understand much because I had just started. What's the problem?
export default async () => {
const [isLoading, setIsLoading] = React.useState(true);
const [userToken, setUserToken] = React.useState(null);
const AsyncUserValue = await AsyncStorage.getItem('userid');
console.log(AsyncUserValue); // (userid 15)
if(AsyncUserValue != null){
console.log('AsyncStorageParse: ' + AsyncUserValue); // (userid 15)
setUserToken(AsyncUserValue);
console.log('Tokken: ' + userToken); // NULL
}
React.useEffect(() => {
setTimeout(() =>{
setIsLoading(false);
}, 1000);
}, []);
if(isLoading) { return <SplashScreen /> }
return(
<NavigationContainer>
{userToken ? (
<AppTabs />
) : (
<LoginStack />
) }
</NavigationContainer>
)
}
You returned functional component as asynchronous (note top export default async ()).
You can't do that - components are required to return React elements (so they have to be synchronous).
What you can do instead is to create a inner async function and do all your async logic there:
export default () => {
const [state, updateState] = useState();
async function myWork() {
const data = await getDataAsyncWay();
updateState(data);
}
useEffect(() => {
myWork()
}, [])
return <View>{...}</View>
}
Note: avoid exporting anonymous function as components - this way, their name won't be visible in stack trace (see your screenshot). What you can do instead is:
function MyComponent() {...};
export default MyComponent