2

Hopefully I can explain the issue I'm having.

I have a button that triggers a callback function to initiate a POST request, aiming to save favorite job posts. The endpoint for this request is connected to my backend using Python with Flask. In the backend, I've set up a conditional statement that prevents a user from saving a job post if it's already saved in the database.

Although most of my code seems to function as intended, there's a behavior I'm observing during testing. When a user tries to save a job that's already saved, the system correctly returns a 400 HTTP status code, which is the desired outcome. However, after this point, when attempting to save a different job (one that isn't already saved), I'm still receiving the same 400 status code.

Interestingly, on the third attempt, regardless of whether the job is already saved or not, the request goes through with a 201 status code. Upon investigating the POST data, I've realized that the previous job I tried to save is now stored in the database, and the job I've just clicked on isn't being saved.

In simpler terms, it appears that there's a delay in my onClick handler's execution with each click. The job ID logged to the console corresponds to the job from the previous click, rather than the current one.

This is my current code,

Backend Python code (Favorites class in Flask):

class Favorites(Resource):
    def post(self):
        request_json = request.get_json()
        job_id = request_json.get('job_id')
        user_id = request_json.get('user_id')

        # Check if the job is already favorited by the user
        existing_favorite = Favorite.query.filter_by(job_id=job_id, user_id=user_id).first()
        if existing_favorite:
            return make_response({"error": "Job already saved"}, 400)  # Use 400 for bad request
        
        # If the job is not already favorited, proceed to create the favorite entry
        new_favorite = Favorite(
            employer_logo=request_json.get('employer_logo'),
            job_title=request_json.get('job_title'),
            employer_name=request_json.get('employer_name'),
            job_city=request_json.get('job_city'),
            job_state=request_json.get('job_state'),
            job_min_salary=request_json.get('job_min_salary'),
            job_max_salary=request_json.get('job_max_salary'),
            job_employment_type=request_json.get('job_employment_type'),
            job_apply_link=request_json.get('job_apply_link'),
            job_description=request_json.get('job_description'),
            job_qualifications=request_json.get('job_qualifications'),
            job_responsibilities=request_json.get('job_responsibilities'),
            job_benefits=request_json.get('job_benefits'),
            job_id=job_id,
            user_id=user_id
        )

        try: 
            db.session.add(new_favorite)
            db.session.commit()
            return make_response(new_favorite.to_dict(), 201)  # Use 201 for created
        
        except Exception as e:
            print(e)
            return make_response({'error': 'Unprocessable Entity'}, 500)  # Use 500 for server error

    def get(self):
        # Retrieves all favorite jobs
        favorites = [favorites.to_dict() for favorites in Favorite.query.all()]
        return make_response(jsonify(favorites), 200)

api.add_resource(Favorites, '/favorites')

Frontend React code (handling favorite button clicks):

<div className='search-results'>
    <div className='search-query'>
        <h4 className='search-result-header'>
            {searchedJobData && searchedJobData.parameters
                ? searchedJobData.parameters.query
                : "Search for jobs"}
        </h4>
    </div>
    {slicedSearchedJobData?.map((jobInfo, index) => (
        <div onClick={() => handleSelectedIndex(index)} key={`${jobInfo.job_id}-${jobInfo.job_title}`} className='search-job-card'>
            <div className='search-job-card-wrapper'>
                <h4>{jobInfo.job_title}</h4>
                <p className='employer-name'>{jobInfo.employer_name}</p>
                <p>{jobInfo.job_city}, {jobInfo.job_state}</p>
                {jobInfo.job_min_salary && jobInfo.job_max_salary ? <p className='job_salary'>${jobInfo.job_min_salary} - ${jobInfo.job_max_salary}</p> : <p className='job_salary'>$N/A</p>}
            </div>
            <button onClick={handleFavorites} className='bookmark-btn' ><BsBookmark /></button>
        </div>
    ))}
    <button onClick={handleLoadMore} className='load-more-btn'>Load More</button>
</div>

Event handler function for saving favorites:

const handleFavorites = async () => {
    console.log("Sending POST request to favorites API...");
    const favoritesUrl = "http://127.0.0.1:5000/favorites";

    const job_id = selectedJobID;
    const user_id = user.id;
    const job_title = selectedJobTitle;
    const employer_name = selectedEmployer;
    const job_city = selectedJobCity;
    const job_state = selectedJobState;
    const job_min_salary = selectedJobMinSalary;
    const job_max_salary = selectedJobMaxSalary;
    const job_employment_type = selectedJobEmploymentType;
    const job_apply_link = selectedJobApplyLink;
    const job_description = selectedJobDescription;

    console.log(job_id)

    if (!user) {
        alert("Must be signed in to bookmark a job.");
        return;
    }

    try {
        const response = await fetch(favoritesUrl, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                job_id,
                user_id,
                job_title,
                employer_name,
                job_city,
                job_state,
                job_min_salary,
                job_max_salary,
                job_employment_type,
                job_apply_link,
                job_description
            }),
        });

        if (response.ok) {
            // Successfully added to favorites
            const newFavorite = await response.json();
            // Update the newFavoriteJobData state with the newFavorite before checking
            dispatch(setNewFavoriteJobData([...newFavoriteJobData, newFavorite]));
            console.log("Job added to favorites.");
        } else {
            // Handle the case where the server responded with an error
            console.error("Failed to add job to favorites.");
        }
    } catch (error) {
        // Handle network errors
        console.error("An error occurred while adding to favorites:", error);
    }
};

I tested my backend using postman which seems to be working fine on the backend so I'm assuming it's the front end.

0 Answers0