Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in TypeScript code – "Property 'setSelectedFile' does not exist on type 'void'.ts(2339)"

I am getting the above error in my TypeScript code. I am attaching the codes of 2 files along with the error message. Please look into it.

This is the "NewPostForm.tsx" file in which error is occuring.

import React, { useState } from 'react';
import {AlertIcon, Flex, Icon, Alert, Text} from "@chakra-ui/react";
import {BiPoll} from "react-icons/bi";
import { BsLink45Deg, BsMic } from 'react-icons/bs';
import { IoDocumentText, IoImageOutline } from 'react-icons/io5';
import {AiFillCloseCircle, AiTwotoneWallet} from "react-icons/ai";
import TabItem from './TabItem';
import TextInputs from "./PostForm/TextInputs"
import { render } from 'react-dom';
import ImageUpload from './ImageUpload';
import { User } from 'firebase/auth';
import { useRouter } from 'next/router';
import { addDoc, collection, serverTimestamp, Timestamp, updateDoc } from 'firebase/firestore';
import { firestore, storage } from '../../firebase/clientApp';
import { getDownloadURL, ref, uploadString } from 'firebase/storage';
import { Post } from '../../atoms/postsAtom';
import useSelectFile from '../../hooks/useSelectFile';

type NewPostFormProps = {
    user: User;
};

const formTabs = [
    {
        title: "Post",
        icon: IoDocumentText,   
    },

    {
        title: "Images & Video",
        icon: IoImageOutline,
    },

    {
        title: "Link",
        icon: BsLink45Deg,
    },

    {
        title: "Poll",
        icon: BiPoll,
    },

    {
        title: "Talk",
        icon: BsMic,
    },
];

export type TabItem = {
    title: string;
    icon: typeof Icon.arguments;
};

const NewPostForm:React.FC<NewPostFormProps> = ({user}) => {
    const router = useRouter();
    const [selectedTab, setSelectedTab] = useState(formTabs[0].title);
    const [textInputs, setTextInputs] = useState({
        title: "",
        body: "",
    });

    const {selectedFile, setSelectedFile, onSelectFile} = useSelectFile();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);  
    const handleCreatePost = async() => {
        const {communityId} = router.query;
        
        // Create new post object => type Post
        const newPost: Post = {
            communityId: communityId as string,
            creatorId: user?.uid,
            creatorDisplayName: user.email!.split("@")[0],
            title: textInputs.title,
            body: textInputs.body,
            numberOfComments: 0,
            voteStatus: 0,
            createdAt: serverTimestamp() as Timestamp,
            id: ''
        };

        setLoading(true);

        try {
            // Store the post in DB
            const postDocRef = await addDoc(collection(firestore, "posts"), newPost);

            // Check for selected file
            if(selectedFile)
            {
                // Store in storage => getDownloadURL {return imageURL}
                const imageRef = ref(storage, `posts/${postDocRef.id}/image`);
                await uploadString(imageRef, selectedFile, "data_url");
                const downloadURL = await getDownloadURL(imageRef);

                // Update post doc by adding imageURL
                await updateDoc(postDocRef, {
                    imageURL: downloadURL,
                });
            }
            
        // redirect the user back to the communityPage using the router
        router.back();
    }
        catch(error: any)
        {
            console.log("handleCreatePost error", error.message);
            setError(true);
        }

        setLoading(false);
    };

    const onTextChange = (
        event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
    ) => {
        const {
            target: {name, value},
        } = event;
        setTextInputs((prev) => ({
            ...prev,
            [name]: value,
        }));
    };
    
    return <div>
        <Flex direction="column" bg="white" borderRadius={4} mt={2}>
            <Flex width="100%">
                {formTabs.map((item) => (
                    <TabItem key={item.title} item={item} selected={item.title === selectedTab}
                    setSelectedTab={setSelectedTab} />
                ))}
            </Flex>
            <Flex p={4}>
                {selectedTab === "Post" && (
                <TextInputs textInputs={textInputs} handleCreatePost={handleCreatePost} 
                onChange={onTextChange} loading={loading} />)}
                {selectedTab === "Images & Video" && (
                    <ImageUpload 
                    selectedFile={selectedFile}
                    onSelectImage={onSelectFile}
                    setSelectedTab={setSelectedTab}
                    setSelectedFile={setSelectedFile} />
                )}
            </Flex>
            {error && (
                <Alert status="error">
                    <AlertIcon />
                    <Text mr={2}>Error Creating the Post</Text>
                </Alert>
            )}
        </Flex>
    </div>
}
export default NewPostForm;

Also I am attaching another "useSelectFile.tsx" file for reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, {useState} from 'react';

const useSelectFile = () => {
    const [selectedFile, setSelectedFile] = useState<string>();

    const onSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
        console.log("THIS IS HAPPENING", event);
        const reader = new FileReader();
        if(event.target.files?.[0])
        {
            reader.readAsDataURL(event.target.files[0]);
        }

        reader.onload = (readerEvent) => {
            if(readerEvent.target?.result)
            {
                setSelectedFile(readerEvent.target.result as string);
            }
        };
    };

    return 
    {
        selectedFile
        setSelectedFile
        onSelectFile
    };
};

export default useSelectFile;

Also I am attaching the screenshot of error message.
enter image description here

>Solution :

You have return nothing from your hook file and the return object you are expecting is wrong

Try this

 return {
        selectedFile,
        setSelectedFile,
        onSelectFile,
    };

a working sandbox is here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading