reactjs 无法在不包含特定值的情况下推送到DynamoDB

gmxoilav  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(111)

我想将一些数据从表单推送到DynamoDB进行存储。如果我包括营养素数据,这一切都很顺利。当我排除营养素数据时,由于某种原因,推送失败。
除了recipe_indexitem_typerecipe_index是从脚本顶部的查询自动生成的;将item_type手动设置为{S: 'recipe'})。
我没有看到任何东西使它以营养物质的可用性为条件工作,我唯一的线索是Error RequestAbortedError: Request aborted的通用日志,我已经尝试在排除故障的过程中移动并简化这段代码;无济于事。谷歌搜索也不走运。我通常会在错误信息上找到一些东西...
我希望你们中的一个互联网陌生人能把我从自己的愚蠢中拯救出来,因为我确信我忽略了一些应该是显而易见的事情。我对DynamoDB、JS和React还很陌生。

export function SaveCreateButton(props){

    // Load the AWS SDK for Node.js
    var AWS = require('aws-sdk');

    // Create DynamoDB service object
    var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

    // Query for number of items in the table through GSI
    var params = {
        ExpressionAttributeValues: {
            ':type' : {S: 'recipe'},
        },
        KeyConditionExpression: 'item_type = :type',
        TableName: 'recipes',
        IndexName: 'item_type-index',
    };

    const [data, setData] = useState([]);

    useEffect(() => {
        ddb.query(params, function (err, data) {
        if (data) {
            console.log('length: ', data['Items'].length)
            setData(data['Items'].length);
        } else {
            console.log(err);
        }
        });
    }, [props.title]);

    var navigate = useNavigate(); 

    const saveNew = () => {

        var currentTitle = document.getElementById('title').value
        
        var currentYield = document.getElementById('yield').value
        
        var currentTime = document.getElementById('time').value

        var currentPicture = document.getElementById('picture').value

        var instNodes = document.querySelectorAll('[id=instructions]')
        var currentInstructions = Array.prototype.map.call(instNodes, function(t) { return {S : t.value}; });

        var ingNodes = document.querySelectorAll('[id=ingredients]')
        var currentIngredients = Array.prototype.map.call(ingNodes, function(t) { return {S : t.value}; });

        var nvNodes = document.querySelectorAll('[id=nutrientsValue]')
        var currentNutrientsValue = Array.prototype.map.call(nvNodes, function(t) { return {S : t.value}; });          

        var ntNodes = document.querySelectorAll('[id=nutrientsType]')
        for(const element of nt_nodes){
            var regex = /^\s*$|[a-z]|[a-zA-Z]+([A-Z][a-z]+)+$/g
            if (regex.test(element.value) === false){
                element.classList.add('err')
                alert('"' + element.value + '" must be in camelCase.')
                return false
            }
        }
        var currentNutrientsType = Array.prototype.map.call(ntNodes, function(t) { return t.value; });

        var nutrientsMap = {};
        currentNutrientsType.forEach((key, i) => nutrientsMap[key] = currentNutrientsValue[i]);

        // Call DynamoDB to add the item to the table
        var params = {
            TableName: 'recipes',
            Item: {
                'recipe_index': {N: String(data)},
                'title': {S : currentTitle},
                'yields': {S : currentYield},
                'cook_time': {S : currentTime},
                'image': {S: currentPicture},
                'instructions': {L: currentInstructions},
                'ingredients' : {L: currentIngredients},
                'nutrients' : {M: nutrientsMap},
                'item_type' : {S: 'recipe'},
            },
        };
        
        ddb.putItem(params, function(err, data) {
            if (err) {
                console.log("Error", err);
            } else {
                console.log("Success", data);
            }
        });

        // go back to display page and refresh.
        navigate(currentTitle);
        window.location.reload(false);
    }
    return(<button name={props.name} className={props.className} onClick={saveNew} type="button">Save</button>)
}
pw9qyyiw

pw9qyyiw1#

不能将值保存为未定义,未定义营养素时会发生这种情况。
尝试有条件地设定营养

Item: {
                'recipe_index': {N: String(data)},
                'title': {S : currentTitle},
                'yields': {S : currentYield},
                'cook_time': {S : currentTime},
                'image': {S: currentPicture},
                'instructions': {L: currentInstructions},
                'ingredients' : {L: currentIngredients},
                 ...(nutrientsMap==undefined) && {'nutrients':{M: nutrientsMap}},
                'item_type' : {S: 'recipe'},
            }

相关问题