'I'm getting error in my react code im using firebase storage while im passing the thumbnail value and it has name property on that object, error givin
` useForm.js:
import { projectStorage } from '../firebase/config';
import { useAuth } from './useAuth';
export const useForm = () => {
const { user } = useAuth();
const uploadImage = async (thumbnail) => {
const uploadPath = `thumbnails/${user.uid}/${thumbnail.name}`;
try {
const img = await projectStorage.ref(uploadPath).put(thumbnail);
const imgUrl = await img.ref.getDownloadURL();
} catch (err) {
console.log(err.message);
}
};
return { uploadImage };
};`
Form.jsx: `
import { useState } from "react"
import { useForm} from '../hooks/useForm'
export default function Form() {
const [caption, setCaption] = useState('')
const [error, setError] = useState(null)
const [thumbnail, setThumbnail] = useState(null)
const { uploadImage} = useForm()
const handleSubmit = (e) =>{
e.preventDefault()
uploadImage(thumbnail)
}
const handleChange = (e) =>{
setThumbnail(null)
const selected = e.target.files[0]
console.log(selected);
if(!selected){
setError('please select a file')
return
}
if(!selected.type.includes('image')){
setError('please select a image file')
return
}
setError(null)
setThumbnail(selected)
console.log('photo updated');
}
return (
<div className="add-form">
<form onClick={handleSubmit}>
<label>
<span>Photo:</span>
<input type="file" name="file" id="file" onChange={handleChange} required/>
</label>
<label >
<span>caption:</span>
<textarea name="captiom" id="caption" onChange={(e)=>setCaption(e.target.value)}></textarea>
{ error && <p className="error">{Error}</p>}
</label>
<button>Submit</button>
</form>
</div>
)
}
` The above is my code in that useForm.js im using that thumbnail state which is stored in form.jsx and passign through the function to useForm.js so i can create path using that to upload images in firebase storage.
useForm.js:7 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name') getting this error
can someone please help me with what I'm doing wrong please give me the solution
Solution 1:[1]
It looks like this is happening because you aren't validating that thumbnail is actually set inside the handleSubmit function.
So when it reaches this line:
const uploadPath = `thumbnails/${user.uid}/${thumbnail.name}`;
...it can't read .name because thumbnail is null.
Try handling the case where thumbnail is being submitted as null like this:
const handleSubmit = (e) =>{
e.preventDefault();
if(!thumbnail){
setError('please select a file');
return;
}
setError(null);
uploadImage(thumbnail);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CDoe |
